title: Elixir Array Syntactic Sugar

text:
# Question
Title: Elixir Array Syntactic Sugar
In Elixir, (linked) lists are in the format `[head | tail]` where **head** can be anything and **tail** is a list of the rest of the list, and `[]` \- the empty list - is the only exception to this.

Lists can also be written like `[1, 2, 3]` which is equivalent to `[1 | [2 | [3 | []]]]`

Your task is to convert a list as described. The input will always be a valid list (in Elixir) containing only numbers matching the regex `\[(\d+(, ?\d+)*)?\]`. You may take the input with (one space after each comma) or without spaces. The output may be with (one space before and after each `|`) or without spaces.

For inputs with leading zeroes you may output either without the zeroes or with.

Input must be taken as a string (if writing a function), as does output.

## Examples

```
[] -> []
[5] -> [5 | []]
[1, 7] -> [1 | [7 | []]]
[4, 4, 4] -> [4 | [4 | [4 | []]]]
[10, 333] -> [10 | [333 | []]]

```

related, not a duplicate as this in part involves adding mode `]` to the end. Additionally, the Haskell answer here is quite different to the one there.

# Answer
> 9 votes
## Haskell, 50 bytes

```
f.read
f(a:b)='[':show(a+0)++'|':f b++"]"
f _="[]"

```

Try it online!

The `+0` lets the Haskell type checker know that we are dealing with lists of numbers, so `read` will parse the input string for us.

# Answer
> 6 votes
# Python 2, 50 bytes

```
r='%s'
for x in input():r%='[%s|%%s]'%x
print r%[]

```

Try it online!

# Answer
> 4 votes
# JavaScript (ES6), 50 bytes

```
s=>eval(s).map(v=>`[${p+=']',v}|`,p='[]').join``+p

```

Try it online!

---

# Recursive version, 51 bytes

```
f=(s,[v,...a]=eval(s))=>1/v?`[${v}|${f(s,a)}]`:'[]'

```

Try it online!

# Answer
> 4 votes
# Retina, ~~39~~ ~~33~~ ~~32~~ 20 bytes

```
\b]
,]
+`,(.*)
|[$1]

```

Saved 13 bytes thanks to H.PWiz, ovs, ASCII-only, and Neil.
Try it online!

### Explanation

```
\b]
,]

```

If we don't have an empty list, add a trailing comma.

```
+`,(.*)
|[$1]

```

While there are commas, wrap things with `|[ thing ]`.

# Answer
> 4 votes
# Perl 5 `-pl`, ~~31~~ 28 bytes

```
s/\d\K]/,]/;$\=']'x s/,/|[/g

```

Try it online!

# How?

```
-p                    # (command line) Implicit input/output via $_ and $\
s/\d\K]/,]/;          # insert a comma at the end if the list is not empty
$\=']'x s/,/|[/g      # At the end of the run, output as many ']' as there are
                      # commas in the input.  Replace the commas with "|["

```

# Answer
> 3 votes
# Elixir, ~~111~~ 85 bytes

```
f=fn[h|t],f->"[#{h}|#{f.(t,f)}]"
[],_->"[]"
h,f->f.(elem(Code.eval_string(h),0),f)end

```

Try it online!

I have never used Elixir before. Defines a function that takes a string and a reference to itself and returns a string.

# Answer
> 3 votes
# Ceylon, 113 bytes

```
String p(String s)=>s.split(" ,[]".contains).select((x)=>!x.empty).reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");

```

Try it online!

Here is it written out:

```
// define a function p mapping Strings to Strings.
String p(String s) =>
    // we split the string at all characters which are brackets, comma or space.
    s.split(" ,[]".contains)    // → {String+}, e.g.  { "", "1", "7", "" }
    // That iterable contains empty strings, so let's remove them.
    // Using `select` instead of `filter` makes the result a sequential instead of
    // an Iterable.
     .select((x)=>!x.empty)    // → [String*], e.g.   [1, 7]
    // now invert the order.
    // (This needs a Sequential (or at least a List) instead of an Iterable.)
     .reversed                 // → [String*], e.g.   [7, 1]
    // Now iterate over the list, starting with "[]", and apply a function
    // to each element with the intermediate result.
     .fold("[]")                       // → String(String(String, String))
    //    This function takes the intermediate result `t` (for tail) and an element
    //    `h` (for head), and puts them together into brackets, with a " | " in the
    //    middle. This uses String interpolation, I could have used `"+` and `+"`
    //    instead for the same length.
          ((t,h)=>"[``h`` | ``t``]");  // → String

```

Try it online!

As noted by ovs in a (now deleted) comment: If one select the "without spaces" options for input and output indicated in the question, one can safe 3 more bytes (the obvious ones with spaces in them).

If we don't need to parse the input, but just could get a sequence as input, it gets much shorter (69 bytes).

```
String p(Object[]s)=>s.reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");

```

Try it online!

# Answer
> 2 votes
# Python 3, 65 bytes

```
lambda k:"["+''.join(f"{u}|["for u in eval(k))+-~len(eval(k))*"]"

```

Try it online!

If the input could be a list instead, then:

**Python 3, 53 bytes**

```
lambda k:"["+''.join(f"{u}|["for u in k)+-~len(k)*"]"

```

Try it online!

# Answer
> 2 votes
# SNOBOL4 (CSNOBOL4), 114 bytes

```
	I =INPUT
S	N =N + 1
	I SPAN(1234567890) . L REM . I	:F(O)
	O =O '[' L ' | '	:(S)
O	OUTPUT =O '[' DUPL(']',N)
END

```

Try it online!

```
	I =INPUT				;* read input
S	N =N + 1				;* counter for number of elements (including empty list)
	I SPAN(1234567890) . L REM . I	:F(O)	;* get value matching \d until none left
	O =O '[' L ' | '	:(S)		;* build output string
O	OUTPUT =O '[' DUPL(']',N)		;* print O concatenated with a '[' and N copies of ']'
END

```

# Answer
> 2 votes
# Befunge-98 (PyFunge), ~~22~~ 21 bytes

```
'[,1;@j,]';#$&." |",,

```

Try it online!

If there weren't weird restrictions on output, we could do this in 18:

```
'[,1;@j,]';#$&.'|,

```

Fun fact, this is technically a program that does nothing in Python.

# Answer
> 2 votes
# Stax, 19 bytes

```
É▲²:WlÖ└%ï╪☺╒▓"We↨Φ

```

Run and debug it

My first Stax post, so probably not optimal.

Unpacked and commented:

```
U,                      Put -1 under input
  {                     Block
   i                      Push loop index, needed later
    '[a$'|++              Wrap the element in "[...|"
            m           Map
             '[+        Add another "["
                s2+     Get the latest loop index + 2
                   ']*+ Add that many "]"

```

Run and debug this one

# Answer
> 2 votes
# Husk, 22 bytes

```
+:'[J"|[":msr¹₁*₁Lr
"]

```

Try it online!

# Answer
> 2 votes
# Ruby `-p`, 39 bytes

Full program:

```
$_[$&]="|[#$2]"while/(,|\d\K(?=]))(.*)/

```

Try it online!

### Ruby, ~~48~~ 45 bytes

Recursive function:

```
f=->s{(s[/,|\d\K(?=])/]&&="|[")&&f[s+=?]]||s}

```

Try it online!

# Answer
> 2 votes
# , ~~84~~ ~~71~~ 69 bytes

```
function(x){while(x<(x=sub('(,|\\d\\K(?=]))(.+)','|[\\2]',x,,T)))1;x}

```

Try it online!

* -15 bytes thanks to @KirillL.

# Answer
> 1 votes
# Jelly, 18 bytes

```
ŒVḢ,ŒṘÇ”|;ƲƊ¹¡⁾[]j

```

Try it online!

# Answer
> 1 votes
# Proton, 57 bytes

```
k=>"["+''.join(str(u)+"|["for u:(e=eval(k)))+-~len(e)*"]"

```

Try it online!

# Answer
> 1 votes
# Jelly, 19 bytes

```
ŒV©;€⁾|[”[;µ®L‘”]ẋṭ

```

Try it online!

A non-recursive alternative to Erik's solution.

# Answer
> 1 votes
# Jelly, 18 bytes

```
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$

```

A full program printing the result (as a monadic link it accepts a list of characters but returns a list of characters and integers).

**Try it online!**

### How?

```
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$ - Main link: list of characters  e.g. "[10,333]"
ŒV                 - evaluate as Python code              [10,333]
  µ                - start a new monadic chain, call that X
   ⁾[]             - list of characters                   ['[',']']
      j            - join with X                          ['[',10,333,']']
        ⁾|[        - list of characters                   ['|','[']
       j           - join                                 ['[','|','[',10,'|','[',333,'|','[',']']
           ṫ3      - tail from index three                ['[',10,'|','[',333,'|','[',']']
                 $ - last two links as a monad (f(X)):
              ”]   -   character                          ']'
                ṁ  -   mould like X                       [']',']'] (here 2 because X is 2 long)
             ;     - concatenate                          ['[',10,'|','[',333,'|','[',']',']',']']
                   - implicit (and smashing) print        [10|[333|[]]]

```

# Answer
> 1 votes
# Standard ML, 71 bytes

```
fun p[_]="]|[]]"|p(#","::r)="|["^p r^"]"|p(d::r)=str d^p r;p o explode;

```

Try it online! Uses the format without spaces. E.g. `it "[10,333,4]"` yields `"[10|[333|[4]|[]]]]"`.

**ungolfed**

```
fun p [_]       = "]|[]]"          (* if there is only one char left we are at the end *)
  | p (#","::r) = "|[" ^ p r ^ "]" (* a ',' in the input is replaced by "|[" and an closing "]" is added to the end *)
  | p (d::r)    = str d ^ p r      (* all other chars (the digits and the initial '[') are converted to a string and concatenated to recursive result *)

val f = p o explode  (* convert string into list of chars and apply function p *)

```

Try it online!

# Answer
> 1 votes
# Java 10, 107 bytes

```
s->{var r="[]";for(var i:s.replaceAll("[\\[\\]]","").split(","))r="["+i+"|"+r+"]";return s.length()<3?s:r;}

```

Try it online.

**Explanation:**

```
s->{                       // Method with String as both parameter and return-type
  var r="[]";              //  Result-String, starting at "[]"
  for(var i:s.replaceAll("[\\[\\]]","")
                           //  Removing trailing "[" and leading "]"
             .split(","))  //  Loop over the items
    r="["+i+"|"+r+"]";     //   Create the result-String `r`
  return s.length()<3?     //  If the input was "[]"
          s                //   Return the input as result
         :                 //  Else:
          r;}              //   Return `r` as result

```

# Answer
> 1 votes
# , ~~140~~ 136 bytes

Down 4 bytes as per Giuseppe's sound advice.

```
function(l,x=unlist(strsplit(substr(l,2,nchar(l)-1),", ")))paste(c("[",paste0(c(x,"]"),collapse=" | ["),rep("]",length(x))),collapse="")

```

Try it online!

# Answer
> 1 votes
# , 108 bytes

```
function(l)Reduce(function(x,y)paste0("[",x,"|",y,"]"),eval(parse(t=sub("]",")",sub("\\[","c(",l)))),"[]",T)

```

Try it online!

It took almost a year to find a better R solution than previous...should have known `Reduce` would be the answer! Outputs without spaces, input can be with or without spaces.

# Answer
> 0 votes
# Python 2, 63 bytes

```
lambda s:'['+'|['.join(map(str,eval(s))+[']'])+']'*len(eval(s))

```

Try it online!

# Answer
> 0 votes
# sed + `-E`, 46 bytes

```
:
s/\[([0-9]+)(, ?([^]]*)|())\]/[\1 | [\3]]/
t

```

A fairly straightforward approach. The second line takes `[\d+, ...]` and changes it to `[\d | [...]]`. The third line jumps back to the first line, if the substitution was successful. The substitution repeats until it fails and then the program terminates. Run with `sed -E -f filename.sed`, passing input via stdin.

# Answer
> 0 votes
# Red, 110 bytes

```
func[s][if s ="[]"[return s]replace append/dup replace/all b: copy s",""|[""]"(length? b)- length? s"]""|[]]"]

```

Try it online!

## Explanation of the ungolfed version:

```
f: func[s][
    if s = "[]" [return s]                    ; if the list is empty, return it
    b: copy s                                 ; save a copy of the input in b
    replace/all b "," "|["                    ; replace every "," with "|["
    append/dup b "]" (length? b) - length? s  ; append as many "]" as there were ","
    replace b "]" "|[]]"                      ; replace the first "]" with "|[]]"
]                                             ; the last value is returned implicitly

```

Red is so easily readable, that I doubt I needed adding the above comments :)

# Answer
> 0 votes
# Perl 6, 38 bytes

```
{'['~S:g/\s|.<($/\|\[/~']'x$_+1}o&EVAL

```

Try it online!

---
Tags: code-golf, string, parsing
---


# Question
Title: Compare two integers in C or C++ without comparison operators
Produce the shortest program which takes two signed integers as input (through stdin or as arguments) and displays 3 different outputs depending upon whether the first number is (1) greater than, (2) smaller than, or (3) equal to the second number.

**The Catch**

You cannot use any of the following in your program:

* The standard comparison operators: `<`, `>`, `<=`, `>=`, `==`, `!=`.
* Any library file apart from `conio`, `stdio`, or `iostream`.
* Any non-ASCII or non-printable ASCII character.

**The Winner**

The program with the shortest number of characters wins.

# Answer
> 2 votes
# 53 bytes

```
main(a,b){scanf("%d%d",&a,&b);printf("%ld",0l+a-b);}

```

Only the first character of the output is relevant. The three different outputs are:

1. '-' if b \> a
2. '0' if a == b
3. any other character if a \> b

It works for the full input range of int on all platforms where sizeof(long) \> sizeof(int).

Edit: it costs one extra character to make case 3 print a '+' uniquely instead:

```
main(a,b){scanf("%d%d",&a,&b);printf("%+ld",0l+a-b);}

```

# Answer
> 6 votes
## 90 bytes

If we can use `stdio`, why not use its formatting capabilities to perform comparison?

```
main(a,b){scanf("%d%d",&a,&b);snprintf(&a,2,"%d",b-a);a&=63;putchar(51-!(a-45)-!!(a-48));}

```

Assumes ASCII-compatible encoding and little-endianness.

## 72 bytes

Quotients are rounded toward zero but right-shifts are (in practice) "rounded down". That's a dead giveaway.

```
main(a,b){scanf("%d%d",&a,&b);a-=b;putchar(a?a|=1,a/2-(a>>1)?60:62:61);}

```

## ~~65~~ 79 bytes

Another distinguishing property of negative numbers is that they produce negative modulo. This one doesn't depend on integer representation at all; it even works on my 8-bit excess-127 toaster! Oh, and since we can use `conio`, why not save two bytes with `putch`? Now, if I could only find my copy of TurboC...

```
main(a,b){scanf("%d%d",&a,&b);long long d=a;d-=b;putch(d?d|=1,d%2-1?60:62:61);}

```

**EDIT**: Handle large differences assuming `long long` is wider than `int`.

# Answer
> 6 votes
Maybe I'm missing something in the rules, but...

# 81 bytes

```
main(a,b){scanf("%d%d",&a,&b);long long l=a;l-=b;printf("%lld%d",--l>>63,l>>63);}

```

Ouputs `00` if `a > b`, `-10` if `a == b`, and `-1-1` if `a < b`.

# Answer
> 5 votes
# ~~64~~ 61 characters

```
main(a,b){scanf("%d%d",&a,&b);for(a-=b;a/2;a/=2);putchar(a);}

```

Prints the character values of -1, 0, and 1 for less than, equal to, or greater than, respectively.

This implementation relies on undefined behavior for `b` being of type `int` and for inputs outside the range `INT_MIN / 2` to `INT_MAX / 2`. On platforms where signed overflow wraps around, whether 2s-complement (basically all of them) or sign-magnitude, it will fail for 25% of possible pairs of valid `int`. Interestingly (to me anyway), it will work correctly on platforms where signed overflow saturates.

# Answer
> 4 votes
## ~~59~~  54 characters

54 charcters with a compiler like gcc which doesn't balk at `main(x,y)`:

```
main(x,y){scanf("%d%d",&x,&y);y-=x;putchar(y>>31|!y);}

```

59 characters otherwise:

```
main(){int x,y;scanf("%d%d",&x,&y);y-=x;putchar(y>>31|!y);}

```

Output:

* ASCII code 0x00 if x \< y
* ASCII code 0xFF if x \> y
* ASCII code 0x01 if x == y

# Answer
> 3 votes
## ~~66~~ 102 bytes

```
main(a,b,c,d,e){scanf("%d %d",&a,&b);e=1<<31;c=a&e;d=b&e;putchar(a-b?c&~d?48:d&~c?49:a-b&e?48:49:50);}

```

Reads the integers from STDIN and prints `0` (a \< b), `1` (a \> b) or `2` (a == b).

**Edit:** Now it should also work for differences which are too large to fit into a 32-bit integer. I'm sure That nested ternary can be shortened with some more bit-magic.

# Answer
> 3 votes
# 52 bytes

Sadly this one only works for positive integers, but I thought the concept of using purely arithmetic operators was interesting:

```
main(a,b){scanf("%d%d",&a,&b);putchar(b%a/b-a%b/a);}

```

### Outputs:

* ASCII code 0xFF: a less than b
* ASCII code 0x00: a equal to b
* ASCII code 0x01: a greater than b

# Answer
> 2 votes
# 66 bytes

```
main(a,b){scanf("%d%d",&a,&b);putchar((0l+b-a>>63)-(0l+a-b>>63));}

```

Prints the byte 0x00 if `a == b`, 0x01 if `a < b` and 0xff if `a > b`.

Since *non-ASCII or non-printable ASCII character in \[my\] program* and *if anything is not explicitly forbidden in the question, then it is permitted*, unprintable character in the **output** should be completely fine.

# Answer
> 2 votes
# 87 characters

```
main(a,b,c){scanf("%d%d",&a,&b);c=1<<31;a+=c;b+=c;puts(a^b?(unsigned)a/b?">":"<":"=");}

```

Using the 2^31 trick to convert to unsigned int's

Casting the division to unsigned to handle the upper bit as data, not sign

Using ^ to XOR a and b, when they are equal this returns 0

Using nested conditionals (?) to get "\<","\>", or "=" to feed to puts()

# Answer
> 2 votes
In 64 chars without stdio.h

`a,b;main(){scanf("%d%d",&a,&b);puts((a-b)>>31?"<":a^b?">":"=");}`

prints '\>' if a \> b, '\<' if a \< b, '=' if a == b int overflow is UB. Just don't overflow.

```
// declare a and b as ints
a,b;

// defaults to int
main()
{
  scanf("%d%d",&a,&b);
   /*
    * (a-b)>>31 signbit of a-b
    * a^b a xor b -> 0 if they are equal
    */
  puts(((a-b)>>31) ? "<" : (a^b) ? ">" : "=");
}

```

# Answer
> 1 votes
# ~~88~~ 89 bytes

```
main(a,b){scanf("%d%d",&a,&b);a+=1<<31;b+=1<<31;for(;a&&b;a--)b--;putchar(a?b?48:49:50);}

```

This starts by adding `1<<31` (`INT_MIN`) to a and b, so that 0 now corresponds `INT_MIN`. Then loops and decrements a and b every loop until either is 0, then prints 0, 1 or 2 depending on whether a, b or both are 0.

# ~~120~~ 119 bytes

```
main(a,b,c){scanf("%d%d",&a,&b);c=1<<31;a^=c;b^=c;for(c~=c;!c;c/=2)if(a&c^b&c){putchar(a?48:49);return;}putchar(50);}

```

It's not the shortest solution as it is but might be golfed down a bit by better golfer than me. (Or just people with more knowledge of C than me)

The idea is to mask each bit, starting from the left one and checking for inequality. The rest should explain itself. Since negative numbers start with a 1 bit, I first invert the first bit with `a^=1<<31`.

# Answer
> 1 votes
## 71 bytes

```
main(x,y,z){scanf("%d%d",&x,&y);putchar((z=x-y)?(z&(z>>31))?50:49:51);}

```

http://ideone.com/uvXm6c

# Answer
> 1 votes
## 68 characters

```
int main(a,b){scanf("%d%d",&a,&b);putchar(a-b?((unsigned)a-b)>>31:2);}

```

Puts ASCII character 1, 2 or 3 for less than, greater than or equal, respectively.

# Answer
> 1 votes
I think I'm not even going to try at writing short code. What I will attempt is to perform this comparison in a way that is portable per the C99 spec.

```
int a, b;   // Let's assume these are initialized
int sign_a = a ? ((a|7)^2)%2 + ((a|7)^3)%2 : 0;

```

The modulo operator preserves sign, but it may well produce a zero (including negative zero), so we ensure we have both an odd and even value for it to check (even without knowing if we are using ones complement). Arithmetic operations may overflow, but bitwise will not, and by ensuring there are bits both set and cleared we avoid inadvertently converting our number into negative zero or a trap value. The fact that two operations are required to do so oddly should not matter, because the possible trap representation doesn't cause undefined behaviour until put in an lvalue. Doing the operation with bit 0 toggled ensures we get exactly one non-zero remainder. Armed with the knowledge of both signs, we can decide how to proceed with the comparison.

```
char result="\0<<>=<>>\0"[4+3*sign_a+sign_b]
if (!result) {   // signs matching means subtraction won't overflow
  int diff=a-b;
  int sign_diff=diff ? (diff|7^2)%2 + (diff|7^3)%2 : 0;
  result = ">=<"[1-sign_diff];
}

```

This method may be one of a few that permit extracting the sign of an integer negative zero. We solve that by explicitly checking for zero. If we were golfing for real, we could of course allow the comparison of two zeros to also perform the subtraction.

# Answer
> 1 votes
## C 80 chars

```
a,b,c=1<<31;main(){scanf("%d%d",&a,&b);putchar(a^b?(a&c^b&c?a:a-b)&c?60:62:61);}

```

It prints '\<', '\>' or '=', as it should.

## C 63 chars

A new approach:

```
a;main(b){scanf("%d%d",&a,&b);putchar(50+(0L+a-b>>42)+!(a-b));}

```

Prints '1', '2' or '3'.

---
Tags: code-golf, restricted-source, c, c++
---


title: (bit)Wise Images

text:
# Question
Title: (bit)Wise Images
Given a truth table and two images, use the truth table as a bitwise operation to the two images.

For example with the truth table:

```
  1 0
1 0 0
0 1 0

```

(Note that the top is the first image and the left is the second)

and the two images `(0, 2, 4)` (a `1x1` image, with the numbers being RGB values) and `(30, 20, 10)`:

You would apply the above truth table to the numbers `0` and `30`, of which's binary representations are `00000` and `11110`. Using the truth table as a bitwise operation would get us `00000`, or in decimal form `0`.

This means that the red value of the first pixel would be `0`.

Continuing this with the other RGB values would get us `2` and `4` for green and blue respectively.

So the output for this would be a `1x1` image with the only pixel having an RGB value of `0, 2, 4`.

For images greater than `1x1`, you apply the truth table for both corresponding pixels on both images and output it to the output image.

For example, if we had a pixel which is located at (x, y) in the image, you would apply the truth table to the R, G, and B values for the (x, y) position in the first image and the (x, y) position in the second. Once you have done this, the (x, y) position in the output image is the output of the truth table applied to the R, G, and B values.

**NOTES:**

You can use any default input or output method.

You can assume that the two input images are the same dimensions.

You can use any Standard Image I/O that supports RGB.

The truth table can be in any format you want.

As always, since this is code golf, **lowest byte-count wins**!

# Answer
# APL (Dyalog Unicode), 3 bytesSBCS

Full program. Prompts for first image, then truth table, then second image, all from STDIN. Images must be given as bit arrays (for example, 8 × height × width × 3, but this doesn't actually matter). The truth table must be given as a Boolean APL function. *And yes, those are three identical boxes:*

```
⎕⎕⎕

```

Try it online!

prompt for the first image

prompt for the function, and apply it with the following left argument:

prompt for the second image
> 4 votes

---
Tags: code-golf, image-processing, bitwise
---


title: Average Idle-Dice Rolling

text:
# Question
Title: Average Idle-Dice Rolling
So I ran into this progressive/idle game cleverly called Idle Dice. Has a variety of random effects applied to a pretty typical progression formula game. Warning, time sink! Play at your own risk.

However after you have 5 dice (summed the usual way) along with some bonuses for various matches (pair, two pair, three of a kind, etc), but after that you eventually get *multiplier* dice. These five dice are all multiplied against the total rolled by the first five dice and multiplicatively combine with each other.

Even later on you get access to a roulette wheel which can (if it lands on the right wedges) "skip 10 minutes." Sometimes longer, but all intervals are some multiple of 10 minutes.

# Your task:

Given the multiplier dice I have, how much will I make when I land on the "skip 10 minutes" wedge of the roulette wheel (figuring I can calculate the 20 minute and 1 hour wedges from there)? We'll ignore any upgraded multipliers and focus solely on the flat base values of each die (incremental games, being what they are, get to obscenely large values in a hurry).

## Input

* Five values in any reasonable format. Each value represents the number of faces of each of the five multiplier dice.
    + Missing dice can either be explicitly specified (as 0) or left absent, your choice as long as it is made clear how your program accepts it.
    + You can assume input values of 0, 2, 4, 6, 8, 10, 12, 20, and 100 will be used.
    + For example an input of `[6,6,4,2]` would indicate that there are 2 six-sided multiplier dice, 1 four sided, and 1 two sided, while `6 6 4 2 0` would also be acceptable.

## How the dice roll

* All ten dice are rolled once a second
* The five base dice are summed
* The sum is multiplied by each of the five multiplier's dice's face value
* That total is multiplied by the score bonus (if any)

## The dice

* The five basic (six sided) dice will be assumed all present.

## Score bonus values:

We'll assume the following score multipliers (which apply to the face results of the base 5 dice, not the multiplier dice):

* Pair: 2
* Triplet: 7
* Two-Pair: 5
* Four of a Kind: 60
* Straight: 20
* Full House (pair + triplet): 30
* Five of a Kind: 1500

This page has the odds listed out for the likelyhood of any given result, except a straight for some reason, which is `240/7776` (what's called a Large Straight, rather than a Short Straight).

**Note:** My original test cases were computed using an incorrect value of 2600/7776 odds for a Pair (correct value should be 3600). Given the existing answers, I am not fixing this.

## Output:

Compute the *expected average total* over a 10 minute period (600 rolls) based on the inputs provided, assuming all dice are uniformly distributed. Output need only be accurate to the nearest whole value, but more precision is allowed.

## Test cases

<sub>*Two extra decimal-fractions of precision included for convenience.*</sub>

```
[2] -> 111643.52
[4] -> 186072.53
[6] -> 260501.54
[8] -> 334930.56
[10] -> 409359.57
[12] -> 483788.58
[20] -> 781504.63
[100] -> 3758665.12
[2,2,2] -> 251197.92
[4,2,2] -> 418663.19
[6,6,6] -> 3191143.90
[2,2,2,2,2] -> 565195.31
[6,6,6,6,6] -> 39091512.83
[10,8,6,4,2] -> 24177799.48
[100,20,2,2,2] -> 133197695.3
[100,20,12,2,2] -> 577190013.02
[100,20,12,10,8] -> 6349090143.23
[100,100,100,100,100] -> 24445512498226.80

```

# Answer
> 7 votes
# , ~~50~~ 32 bytes

```
function(M)prod(M/2+.5)*691250/9

```

Try it online!

-17 Bytes thanks to Nick Kennedy, and thanks to Jonathan Allan for suggesting a precision fix, with no byte loss!

Ignores any missing bonus dice. Just a brute force approach.

Works pretty well, but `integers` get promoted to `doubles` once we get past the 2-billion mark (`2^31-1`), leading to a loss of precision.

Because the "regular" and "bonus" dice are independent, \\$E\[RB\]=E\[R\]E\[B\]\\$, easing the calculations to simply calculating \\$E\[B\]\\$ (which is again the `prod` of the expected values of each die) and scaling by \\$E\[R\]\\$, easily calculated from the given test cases.

# Answer
> 5 votes
# Jelly, 16 bytes

```
‘HP×“¡LT⁼þd+’÷Ø%

```

Try it online!

```
‘              Add 1 to each input element
 H             Halve; this is the expected value of each die.
  P            Product.
   ×“¡LT⁼þd+’  Multiply by 319670173900294.
   ÷Ø%         Divide by 2^32.
               319670173900294/2^32 is approximately 74429.01234615,
                 the expected value of the dice before the multiplier.

```

By the law of total expectation, the expected product of independent random values is the product of the expected values. The expected value of each n-sided multiplier die is simply (n+1)/2.

# Answer
> 1 votes
# JavaScript, 35 bytes

Port of Giuseppe's R solution.

```
a=>a.map(n=>x*=++n/2,x=74429.01)&&x

```

Try It Online!

# Answer
> 1 votes
# Japt, ~~19~~ 18 bytes

```
rÈ*°Y/2}6028750/81

```

*-1 byte thanks to @Shaggy*

Try it online!

With slightly less precision: 17 bytes

```
rÈ*½*(YÄ}74429.01

```

# Answer
> 1 votes
# 05AB1E, 12 bytes

```
>;P•₅·e•*81/

```

Port of *@lirtosiast*'s Jelly answer combined with *@JonathanAllan*'s comment (which states \\$6028750/81 == 964600\*600/6/6/6/6/6\\$).

Try it online or verify all test cases.

**Explanation:**

```
>             # Increase each value in the (implicit) input-list by 1
              #  i.e. [100,20,12,2,2] → [101,21,13,3,3]
 ;            # Halve each value in the list
              #  i.e. [101,21,13,3,3] → [55.5,10.5,6.5,1.5,1.5]
  P           # Take the product of this list
              #  i.e. [55.5,10.5,6.5,1.5,1.5] → 7754.90625
   •₅·e•*     # Multiply it by the compressed integer 6028750
              #  i.e. 7754.90625 * 6028750 → 46752391054.6875
         81/  # Then divide it by 81
              #  i.e. 46752391054.6875 / 81 → 577190013.0208334
              # (and output implicitly as result)

```

See this 05AB1E answer of mine (section *How to compress large integer?*) to understand why `•₅·e•` is `6028750`.

---
Tags: code-golf, statistics
---


# Question
Title: Check if all vowels exist in pairs of strings
Your program should find the number of string pairs (pairs of 2) that contain all vowels (a e i o u), when given an integer `N` and `N` strings.

There are easy ways to do this, but I'm looking for the quickest possible solution.

**Example**:

**INPUT:**

```
4
password
unique
orbiting
ointmental

```

**OUTPUT:**

```
2

```

**EXPLANATION:**

`password` has `a,o`

`unique` has `u,e,i`

`orbiting` has `o,i`

`ointmental` has `o,i,e,a`

---

The pairs

`password` and `unique`

`ointmental` and `unique`

are the `2` successful combinations.

---

Here's a sample DataSet  where `N` = 10000

# Answer
> 4 votes
# Java openjdk8

Using bit arrays,

Coding each word on an int where if `a` is present the lowest bit is 1, if `e` the second is 1, etc.

For example `password` has a and o, so its code is `1|8` == `9` == `0b01001`. As we only need the number of pairs we can store the number of words for each code in an array of size 32.

Then for each pair of different indexes except the last (31) where first is less than second and where bitwise or of indexes is 31, we multiply the number of words with code, and the last is particular because it's the only one that can make a pair with a word of the same code, and also with any word.

```
public static void main( String[] args ) {
    int[] a = new int[ 32 ];
    int count = 0;
    try (Scanner scan = new Scanner( System.in )) {
        while ( scan.hasNext() ) {
            String s = scan.next();
            a[ code( s ) ]++;
        }
    }

    int t = 0;
    for ( int i = 0 ; i < 31 ; ++i ) {
        count += a[ i ];
        for ( int j = i + 1 ; j < 31 ; ++j ) {
            if ( ( i | j ) == 31 ) {
                t += a[ i ] * a[ j ];
            }
        }
    }

    t += a[ 31 ] * count + a[ 31 ] * ( a[ 31 ] - 1 ) / 2;
    System.out.println( t );
}

// a e i o u
// 1 2 4 8 16
public static int code( String s ) {
    int r = 0;
    for ( char c : s.toCharArray() ) {
        r |= c == 'a' ? 1 : c == 'e' ? 2 : c == 'i' ? 4 : c == 'o' ? 8 : c == 'u' ? 16 : 0;
    }
    return r;
}

```

TIO

# C++

translating to C++ is straightforward

test with 100 first words

test on TIO with 10000 words of dataset

```
1968503

Real time: 0.419 s
User time: 0.315 s
Sys. time: 0.099 s
CPU share: 98.83 %
Exit code: 0

```

# Answer
> 3 votes
# APL (Dyalog Unicode)

Two solutions designed by my esteemed colleague Marshall, master of speeding up APL. The formulas used are both in '70s APL, so they works in APL\360 on an IBM/360 mainframe. They are anonymous prefix functions taking a character matrix as argument. `N` is not needed but may be supplied as optional (and ignored) left argument.

### The first solution is *O*(*n*2)

A naive approach:

```
{0.5×(+/,(⍉i)∧.∨i)-+/∧⌿i←∨/'aeiou'∘.=⍵}

```

Try it online!

Processes\* the large data set in about 4.5 ms. TIO takes about twice that.

`{``}` "dfn"; the argument is :

`'aeiou'∘.=⍵` equality 3D array with vowels along the first axis, words along the middle axis and characters along the last axis

`∨/` OR-reduction along the last axis; this gives us a 5-row table with one column per word

`i←` store that in `i` (for **i**n)

`∧⌿` AND-reduction along the first axis; this gives us a mask of words that contain all vowels

`+/` sum; count of words containing all vowels (we need to discount their "self-pairs")

`(``)-` subtract that from the following:

`(⍉i)∧.∨i` the Boolean matrix where the OR of corresponding masks is all-true.

`,` ravel (flatten)

`+/` sum; this gives us the count of ordered pairs

`0.5×` halve; this gives us the count of unordered pairs

### The second solution is *O*(*n*)

Breaks even with the above *O*(*n*2) solution at about 150 words of 10 evenly distributed characters. It requires 0-based indexing, and a pre-computed 32-by-32 Boolean vowel signature pairing table:

```
{
    a←0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
    a[2⊥∨/'aeiou'∘.=⍵]+←1
    (0.5×l×¯1+l←a[31])++/,p×a∘.×a
}

```

Processes\* the large dataset in 0.09 ms. TIO's timing is too inconsistent to make any conclusions, but it is likely that it takes about twice the time here too.

---

* 64-bit Dyalog APL 17.0 on 2.6 Ghz i7-4720HQ

---
Tags: string, combinatorics, fastest-code, alphabet
---


title: Buy the most appropriate items

text:
# Question
Title: Buy the most appropriate items
A store is having a big sale.
If your price reaches $199 or more, you can reduce it by $100.
**You can buy each product only once.**
Here's an example list of products: (in order to simplify, the names of the products are represented by letters)

```
+------+-------+
| name | price |
+------+-------+
| A    | 26.9  |
| B    | 24.9  |
| C    | 49.9  |
| D    | 28.9  |
| E    | 14.9  |
| F    | 16.9  |
| G    | 19.9  |
| H    | 19    |
| I    | 14.9  |
| J    | 14.9  |
| K    | 26.9  |
+------+-------+

```

### Input

* A list of product price, such as the above example.
* `N` the item list size `10 <= N <= 100`
* `X` a price

### Output

The best shopping strategy to save money. Find out the least expensive purchase list with a total price of more than `X`, and output:

* The most appropriate total price (before deduction), for the data above, `X` = $199, and the most appropriate total price is `199.2`

### Notes

* Your code can be a function (method) or a full working program.
* Make your algorithm **as fast as possible** (less time complexity)!
* If codes have the same time complexity, the one which uses less space wins.

# Answer
> 2 votes
# Python 2, \\$O(2^{n/2})\\$

```
import sys
def subsetsum(nums, target):
#    totalsum = sum(nums)
#    if(totalsum == target):
#        return target
#    if(totalsum < target):
#        return -1

    sumsA = {}
    sumsB = {}
    for n in nums[::2]:
        for k,v in sumsA.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsA:
                sumsA[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsA loop: "
                    return target
    minsum = sys.maxsize
    for n in nums[1::2]:
        for k,v in sumsB.items() + [(0,[])]:
            newsum = k + n
            if newsum not in sumsB:
                sumsB[newsum] = v + [n]
                if newsum == target:
                    print "target found in sumsB loop: "
                    return target
                for a in sumsA:
                    combsum = a + newsum
                    if combsum == target:
                        print "target found in combined sumsA and sumsB loop: "
                        return target
                    if combsum > target and combsum < minsum:
                        minsum = combsum
    print "target",target,"not found, so return the closest alternative: "
    return minsum

# Test cases:
print subsetsum([26.9, 24.9, 49.9, 28.9, 14.9, 16.9, 19.9, 19, 14.9, 14.9, 26.9], 199)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 1000)
print subsetsum([47.5, 1.0, 19.6, 16.7, 21.8, 5.6, 40.4, 31.8, 25.4, 21.9,
                 21.7, 17.6, 48.4, 17.4, 41.1, 8.9, 12.2, 25.6, 28.5, 26.3,
                 21.3, 35.1, 37.8, 45.1, 28.5, 47.6, 33.9, 21.5, 34.3, 14.2,
                 40.9, 17.9, 44.9, 44.2, 20.5, 30.8, 43.0, 24.5, 20.1, 46.7,
                 49.6, 42.1, 19.8, 3.8, 0.2, 38.3, 21.3, 15.3, 11.2, 36.0], 555.5)

```

Try it online.

My Python skills are a bit rusty, so if you see any issues, let me know. Also, I think this can be improved in code for sure with some binary searches or something along those lines.

The program uses the Knapsack Meet-in-the-middle approach. It first uses all even-indexed items to get a set of all possible sums for the powerset of these even-indexed items. Then it does the same for all odd-indexed items, and simultaneously determines the minimum sum using the sums of these two sets.

# Answer
> 0 votes
# Jelly, 10 bytes, Score \\$O(2^n)\\$

```
ŒPS€>Ƈ199Ṃ

```

Try it online!

Input is a list of prices for items. Output is the minimum possible price greater than 199. Note this outputs 199.20000000000002 due to floating point rounding. Also note as it stands that it will about the least total price greater than 199 (rather than greater than or equal to).

Time used scales exponentially and is approximately proportional to 2^n where n is the number of items. On TIO, 19 items takes approx. 14.5 seconds.

---
Tags: combinatorics, fastest-algorithm
---


title: A Multipurpose Quine

text:
# Question
Title: A Multipurpose Quine
I personally love quines, but they all seem to be so... static. So why not create a quine that can do *more*.

**Challenge**

The challenge here is to create a quine that without any sort of input is a normal quine. Then if it receives a different input, it outputs a *different* quine in a *different* language. (basically like a polyglot, but it doesn't have to return to the original source code)

EX:

Starting program:

```
James

```

Given no input or 0 as input, the code above outputs:

```
James

```

Given 1 as input, the code outputs:

```
Kendra

```

Given 2 as input, the code outputs:

```
Alexander

```

And so on...

**Requirements**

Like with any other quine challenge, no examining source code directly!

Inputs are either nothing, or a positive integer.

Each quine must not be less than \\$\lceil(n/4)\rceil\\$ levenshtein distance from all other quines, where \\$n\\$ is the length of the original quine. Look at this example program:

```
Bobb  //original quine
Bobby //output (when given an input), we'll name him bobby
Bob   //output (when given a different input), we'll name him bob

```

The above is not valid, because Bob is only one levenshtein distance from Bobb.

However, this one is valid:

```
Bob      //original quine
Alice    //bob's output when given 1 as input
Geronimo //bob's output when given 2 as an input

```

Because \\$ ceil(len(bob)/4)=1 \\$, and Alice, Geronimo, and Bob are all at more than one levenshtein distance away from each other.

There has to be a minimum of one *extra* quine to be outputted.

The quine *must* output itself when given no input or 0, and output a different quine if given a different integer input!

**Points**

Points are based on this equation (courtesy of Luis felipe De jesus Munoz) $${\frac{100}{\text{bytes}} \cdot 2^{\text{extra quines} - 1}}$$

(100 divided by the number of bytes multiplied by 2 to the power of every *different* quine that your program can output, minus one to make sure the program at least outputs one *different* quine)

# Answer
> 3 votes
# Befunge-98, \>\<\>, Fission, Wumpus, Cardinal, Gol\>\<\> and Beeswax, Score: \\$(100/103)\*2^6 = 62.136\\$

```
"[0#34o+]l2:)&o@.0*74#!,!?:o#_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

```

Try it online!

Verification!

When given an input of 0, this program produces itself. When given a different number, it produces the quines in the format

```
"[0#34o+]l2:)&o@.0*74#!,!?:o1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 #_4F.~6.@1~0@D~FJR'!+!7,++tttt=++%88-$@,kJ'$.k+bf:k+bfj*a!:&,k-.#!0+df+c+f7

```

Where the `1`s are the input number. Since there are 26 copies of the `1`, this makes each quine distinct at least \\$bytes/4\\$ Levenshtein distance. The quines are entirely interchangeable as no program actually cares about the number part. I might see if I can add some more 2D languages to this ~~(I'm thinking Cardinal Gol\>\<\> next)~~ Don't have one in mind right now.

# Answer
> 1 votes
**JAVA -\> \>\<\>, (100/460 bytes)\*2^0 = a score of .217... yay**

```
import java.util.Scanner;public class M{public static void main(String args[]){Scanner i=new Scanner(System.in);String s="import java.util.Scanner;public class M{public static void main(String args[]){Scanner i=new Scanner(System.in);String s=%c%s%c;if(i.nextInt()==0){System.out.printf(s,34,s,34,34,34);return;}System.out.println(%c'r3d*d8*7+e0p>>|%c);}}";if(i.nextInt()==0){System.out.printf(s,34,s,34,34,34);return;}System.out.println("'r3d*d8*7+e0p>>|");}}

```

I'm not winning my own challenge, but this should serve as an example.

If it gets and input of 0 then it outputs the java quine, if it receives a 1 then it outputs a \>\<\> quine (courtesy of mbomb007). And that is it...

---
Tags: number, code-challenge, quine, rosetta-stone
---


title: Holiday Gift Exchange

text:
# Question
Title: Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

## PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

1. Each person buys one gift and receives one gift.
2. Nobody buys their own gift.
3. Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

## INPUT

None.

## OUTPUT

Formatted as in this example:

> Andy buys for Barb
> Barb buys for Carl
> Carl buys for Didi
> Didi buys for Earl
> Earl buys for Fran
> Fran buys for Andy

# Answer
## J, 57

```
(,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'

```

eg

```
   (,.' buys for ',"1|.)(?~6){6 4$'AndyBarbCarlDidiEarlFran'
Carl buys for Earl
Andy buys for Barb
Fran buys for Didi
Didi buys for Fran
Barb buys for Andy
Earl buys for Carl

```
> 4 votes

# Answer
# Japt -R, 41 bytes

```
`AÌ)B¼C¤E¤FÎÂDi¹`qe ö¬ê1 ò mq` ¿ys f

```

-2 bytes thanks to @Oliver!

Try it!

This is the approach I took at a high level:

* uncompress a string containing participants names
* split string into an array
* shuffle it
* assign each person to the person with the next highest index
* the last person in the array gets assigned to the first

I have a little history with this problem as I created a "secret santa" program for my work years ago. We ended up asking a few job applicants to work through it as well :)
> 4 votes

# Answer
# Haskell, 241 189 characters

```
import Data.List
import Random
main=randomRIO(0,719)>>=mapM_ putStrLn.f
f n=map(\(x,y)->x++" buys for "++y).zip(l n).tail$cycle$l n
l=(permutations(words"Andy Barb Carl Didi Earl Fran")!!)

```

Fully random output (that still satisfies the spec).

This generates all permutations of the list of the names, picks one at random (I *think* this is the shortest way in Haskell to shuffle a list - if anyone has anything smaller, I'd appreciate it), and then each person then buys a present for the next person in the list.
> 3 votes

# Answer
## Golfscript: ~~72 64~~ 57 chars

```
"AndyBarbCarlDidiEarlFran"4/{;9rand}${.n+\' buys for '}%(

```

Tests

```
$ golfscript codegolf-838.gs
Fran buys for Carl
Carl buys for Andy
Andy buys for Barb
Barb buys for Didi
Didi buys for Earl
Earl buys for Fran

$ golfscript codegolf-838.gs
Didi buys for Earl
Earl buys for Andy
Andy buys for Barb
Barb buys for Carl
Carl buys for Fran
Fran buys for Didi

```
* Thanks gnibbler for `"AndyBarbCarlDidiEarlFran"4/`, updated and got 7 chars less
* 57 chars solution is basically by Nabb :D, and also noticed that `;9rand` is more random than my `6rand*`
> 3 votes

# Answer
## Windows PowerShell, 83

```
$i=random 5
($n=-split'Andy Barb Carl Didi Earl Fran')|%{"$_ buys for "+$n[++$i%6]}

```

History:

* 2011-02-11 22:01 **(136)** – First attempt.
* 2011-02-11 22:05 **(130)** – Inlined a few things. Shuffling the names now, not the indexes.
* 2011-02-13 16:13 **(128)** – I don't need the modulus as `$i` will be recreated every time.
* 2011-02-13 16:20 **(87)** – Borrowed the idea from Anon.'s C# solution. Just generate a random offset and then just let them gift in circles.
* 2011-02-13 16:26 **(83)** – Changed random number generation and indexing. Pulled `$_` into the string to save the `+`.
> 3 votes

# Answer
c99 -- 252 characters

```
#include <stdio.h>
#define G for(i=0;i<6;i++)
char*n="Andy\0Barb\0Carl\0Didi\0Earl\0Fran",*p[7];int i,j;int main()
{FILE*r=fopen("/dev/random","r");G p[i]=n+5*i;G{j=fgetc(r)%6;p[7]=p[j]
;p[j]=p[i];p[i]=p[7];}G printf("%s buys for %s\n",p[i],p[(i+1)%6]);}

```

Slight improvement by taking advantage of the circular nature of the permutation. This version *always* builds a loop-like buying strategy, so it is less random than the previous (271 character) version, but I believe it still meets the spec.

Requires a platform that has a working `/dev/random`. I ought to be able to knock about 8 off by omitting the `\0`s in the big string, but my libc doesn't seem to be dealing with `%4s` print specifiers the way the man page says.

The shuffle is bad, but doing it that way prevents me from having to check on *"Foo buys for Foo"* conditions.

**Readable:**

```
#include <stdio.h>

char *n="Andy\0Barb\0Carl\0Didi\0Earl\0Fran",
  *p[7]; /* 7th cell for temp */
int i,j;

int main(){
  FILE*r=fopen("/dev/random","r");
  for(i=0;i<6;i++)
    p[i]=n+5*i;   /* Initialize the pointers */
  for(i=0;i<6;i++){
    j=fgetc(r)%6; /* Poor numeric properties. Cest le Code Golf */
    p[7]=p[j];
    p[j]=p[i];
    p[i]=p[7];
  }
  for(i=0;i<6;i++)
    printf("%s buys for %s\n",p[i],p[(i+1)%6]);
}

```
> 3 votes

# Answer
## Python - 118 chars

```
from random import*;L="Andy Barb Carl Didi Earl Fran".split()
for i in sample(range(6),6):print L[i-1],"buys for",L[i]

```

**Python - 120 chars**

```
import random as R;L="Andy Barb Carl Didi Earl Fran".split();R.shuffle(L)
for i in range(6):print L[i-1],"buys for",L[i]

```
> 2 votes

# Answer
**R - 85 characters**

```
paste(n<-sample(c('Andy','Barb','Carl','Didi','Earl','Fran')),'buys for',n[c(6,1:5)])

```
> 2 votes

# Answer
## Python - 154 chars

```
import random as R;L="Andy Barb Carl Didi Earl Fran".split();M=L[:]
while any(map(str.__eq__,L,M)):R.shuffle(M)
for i in zip(L,M):print"%s buys for %s"%i

```
> 1 votes

# Answer
## C#, 210 183 characters

```
using System;class a{static void Main(){var n="Andy Barb Carl Didi Earl Fran".Split();var c=0,i=new Random().Next(1,6);for(;c<6;c++)Console.WriteLine(n[c]+" buys for "+n[(c+i)%6]);}}

```

Heaps of boilerplate :(

This solution isn't totally random - there are always one or more "loops" of people e.g. A-\>C-\>E-\>A, and the offsets are always the same in the loops. However, it is not possible to predict the output of a particular run unless you have part of that output.
> 1 votes

# Answer
# D: 233 Characters

```
import std.random,std.stdio;void main(){auto p=["Andy","Barb","Carl","Didi","Earl","Fran"];auto q=p.dup;o:while(1){for(int i;i<6;++i)if(p[i]==q[i]){randomShuffle(q);continue o;}break;}foreach(i,a;p)writefln("%s buys for %s",a,q[i]);}

```

More Legibly:

```
import std.random, std.stdio;

void main()
{
    auto p = ["Andy", "Barb", "Carl", "Didi", "Earl", "Fran"];
    auto q = p.dup;

    o:while(1)
    {
        for(int i; i < 6; ++i)
            if(p[i] == q[i])
            {
                randomShuffle(q);
                continue o;
            }

        break;
    }

    foreach(i, a; p)
        writefln("%s buys for %s", a, q[i]);
}

```
> 1 votes

# Answer
## Python (175)

```
import random as r
n=['Andy','Barb','Carl','Didi','Earl','Fran']
m=n[:]
r.shuffle(m)
b=' buys for '
for i in n:
 h=m.pop()
 while h==i:
  m.append(h)
  h=m.pop()
 print(i+b+h)

```
> 1 votes

# Answer
# Scheme, 173

Gives one of two solutions.

```
(define(m lst)
    (printf"~v buys for ~v~n"(car lst)(cadr lst))
    (if(eq?(cadr lst)'Andy)0(m(cdr lst)))
)
(m((if(odd?(random 2))reverse values)'(Andy Barb Carl Didi Earl Fran Andy)))

```
> 1 votes

# Answer
# Ruby - 89 chars

```
(a=%w(Andy Barb Carl Didi Earl Fran).shuffle).zip(a.reverse).each{|e|puts e*' buys for '}

```

Output:

```
Andy buys for Didi
Barb buys for Earl
Fran buys for Carl
Carl buys for Fran
Earl buys for Barb
Didi buys for Andy

```
> 0 votes

# Answer
# MathGolf, 41 bytes

```
"δ%è╘+µ√♂JÇ"2/$╦╕ää▐δáw_╪" buys for "+m+n

```

Try it online!

## Explanation

This is not guaranteed to produce each case with equal probability, but it does produce different results each run. One byte could be removed if I had a shuffle operator, but that's for another day.

```
"δ%è╘+µ√♂JÇ"                                push the string "δ%è╘+µ√♂JÇ"
            2/                              split into segments of two characters
              $                             transform to ordinals using base 256
               ╦                            fetch dictionary words (['Andy', 'barb', 'Carl', 'Earl', 'Fran'])
                ╕ää                         Push "didi"
                   ▐                        append to end of list
                    δ                       capitalize all strings in list
                     áw                     sort by random character in each string (shuffle)
                       _                    duplicate TOS
                        ╪                   right-rotate bits in int, list, str
                         " buys for "       push the string " buys for "
                                     +      Add to all strings in list
                                      m+    zip add the two arrays
                                        n   join array with newline

```
> 0 votes

---
Tags: code-golf
---


title: The Binary Fences

text:
# Question
Title: The Binary Fences
## Input:

* An integer `n` in the range `2 <= n <= 10`
* A list of positive integers

## Output:

Convert the integers to their binary representation (without any leading zeroes), and join them all together.
Then determine all binary substrings that form a 'binary fence' using `n` amount of fence posts. The spaces (zeros) between each fence post are irrelevant (at least 1), but the fence posts themselves should all be of equal width.
Here the regexes the binary substrings should match for each `n`:

```
n   Regex to match to be a 'binary fence'   Some examples

2   ^(1+)0+\1$                              101; 1100011; 1110111;
3   ^(1+)0+\10+\1$                          10101; 1000101; 110011011;
4   ^(1+)0+\10+\10+\1$                      1010101; 110110011011; 11110111100001111001111;
etc. etc. You get the point

```

Looking at the `n=4` examples:

```
1010101
^ ^ ^ ^    All fence posts have a width of one 1
 ^ ^ ^     with one or more 0s in between them

110110011011
^^ ^^  ^^ ^^    All fence posts have a width of two 1s
  ^  ^^  ^      with one or more 0s in between them

11110111100001111001111
^^^^ ^^^^    ^^^^  ^^^^    All fence posts have a width of four 1s
    ^    ^^^^    ^^        with one or more 0s in between them

```

We then output the numbers that use binary digits of the matches 'binary fences'.

## Example:

Input: `n=4`, `L=[85,77,71]`

The binary representation of these integer joined together is:
`1010101 1001101 1000111` (NOTE: The spaces are only added as clarification for the example).

Since `n=4`, we look for substrings matching the regex `(1+)0+\10+\10+\1`, in which case we can find two:
`1010101` (at position `(1010101) 1001101 1000111`); and `11001101100011` (at position `101010(1 1001101 100011)1`)

The first binary fence only uses binary digits from `85`, and the second binary fence uses binary digits from all three integers. So the output in this case would be:
`[[85],[85,77,71]]`

## Challenge rules:

* Although it's also mentioned in the example above, the last sentence is an important one: **We output the numbers for which binary digits are used in the 'binary fence' substring.**
* I/O is flexible. Input can be a list/array/stream of integers, space/comma/newline delimited string, etc. Output can be a 2D integer-list, a single delimited string, a string-list, new-line printed to STDOUT, etc. All up to you, but please state what you've used in your answer.
* Output order of the list itself is irrelevant, but the output of each inner list is of course in the same order as the input-list. So with the example above, `[[85,77,71],[85]]` is a valid output as well, but `[[85],[77,85,71]]` is not.
* As you may have already noticed from the example (the `85`), binary-digits can be used multiple times.
* The regexes should match the substring entirely. So `110101` or `010101` aren't ever a valid 'binary fences' (`10101` is however, iff `n=3`).
* Items in the output-list aren't unique, only the binary-positions of the 'binary fences' are unique. If multiple 'binary fences' can be created with the same integer(s), we add them multiple times to the output-list.
For example: `n=2`, `L=[109, 45]` (binary `1101101 101101`) can form these 'binary fence' substrings: `11011` (at position `(11011)01 101101`); `101` (at position `1(101)101 101101`); `11011` (at position `110(1101 1)01101`); `101` (at position `1101(101) 101101`); `11011` (at position `110110(1 1011)01`); `101` (at position `1101101 (101)101`); `101` (at position `1101101 101(101)`), so the output would be `[[109],[109],[109,45],[109],[109,45],[45],[45]]`.
Another example: `n=2`, `L=[8127]` (binary `1111110111111`) can form these 'binary fence' substrings: `1111110111111` (at position `(1111110111111)`); `11111011111` (at position `1(11111011111)1`); `111101111` (at position `11(111101111)11`); `1110111` (at position `111(1110111)111`); `11011` (at position `1111(11011)1111`); `101` (at position `11111(101)11111`), so the output would be `[[8127],[8127],[8127],[8127],[8127],[8127]]`.
* If no valid output is possible, you can return an empty list or some other kind of falsey output (`null`, `false`, throws an error, etc. Again, your call).

## General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:                       Output
                             (the binary below the output are added as clarification,
                             where the parenthesis indicate the substring matching the regex):

4, [85,77,71]                [[85],[85,77,71]]
                             (1010101) 1001101 1000111; 101010(1 1001101 100011)1

2, [109,45]                  [[109],[109],[109,45],[109],[109,45],[45],[45]]
                             (11011)01 101101; 1(101)101 101101; 110(1101 1)01101; 1101(101) 101101; 110110(1 1011)01; 1101101 (101)101; 1101101 101(101)

3, [990,1,3,3023,15,21]      [[990,1,3,3023],[990,1,3,3023],[1,3,3023],[21]]
                             (1111011110 1 11 1)01111001111 1111 10101; 11110(11110 1 11 101111)001111 1111 10101; 1111011110 (1 11 101111001111) 1111 10101; 1111011110 1 11 101111001111 1111 (10101)

2, [1,2,3,4,5,6,7,8,9,10]    [[1,2,3],[2,3],[4,5],[5],[5,6,7],[6,7],[6,7],[8,9],[9],[10]]
                             (1 10 11) 100 101 110 111 1000 1001 1010; 1 (10 1)1 100 101 110 111 1000 1001 1010; 1 10 11 (100 1)01 110 111 1000 1001 1010; 1 10 11 100 (101) 110 111 1000 1001 1010; 1 10 11 100 10(1 110 111) 1000 1001 1010; 1 10 11 100 101 (110 11)1 1000 1001 1010; 1 10 11 100 101 1(10 1)11 1000 1001 1010; 1 10 11 100 101 110 111 (1000 1)001 1010; 1 10 11 100 101 110 111 1000 (1001) 1010; 1 10 11 100 101 110 111 1000 1001 (101)0

3, [1,2,3,4,5,6,7,8,9,10]    [[4,5],[8,9]]
                             1 10 11 (100 101 )110 111 1000 1001 1010; 1 10 11 100 101 110 111 (1000 1001) 1010

10, [1,2,3,4,5,6,7,8,9,10]   []
                             No binary fences are possible for this input

6, [445873,2075]             [[445873,2075],[445873,2075],[445873,2075]]
                             (1101100110110110001 1)00000011011; 110(1100110110110001 100000011)011; 1101100(110110110001 100000011011)

2, [8127]                    [[8127],[8127],[8127],[8127],[8127],[8127]]
                             (1111110111111); 1(11111011111)1; 11(111101111)11; 111(1110111)111; 1111(11011)1111; 11111(101)11111

2, [10,10]                   [[10],[10,10],[10]]
                             (101)0 1010; 10(10 1)010; 1010 (101)0

4, [10,10,10]                [[10,10],[10,10,10],[10,10]]
                             (1010 101)0 1010; 10(10 1010 1)010; 1010 (1010 101)0

```

# Answer
# Husk, 33 bytes

```
ṠṘmȯF-mȯ#öΛΛ=⁰Fzż+C2gQṁḋmëhohttIQ

```

Try it online!

Passes all test cases. This was a difficult challenge and my solution feels somewhat convoluted.

## Explanation

The program loops through the slices of the input, and repeats each as many times as it contains a match of the regex. We want to count only those matches that overlap the binary expansion of every number in the slice. This seems difficult, but it's easier to count those matches that do not use the first number: just remove that number and count all matches. To get the good matches, we thus count all matches, then subtract the number of matches that don't use the first number, and those that don't use last number. The matches that use neither are counted twice, so we must add them back to get the correct result.

Counting the number of matches in a slice is a matter of concatenating the binary expansions and looping over the slices of the result. Since Husk has no support for regexes, we use list manipulation to recognize a match. The function `g` splits a slice to groups of equal adjacent elements. Then we must verify the following:

1. The first group is a 1-group.
2. The number of groups is odd.
3. The number of 1-groups is equal to the first input `n`.
4. The 1-groups have equal lengths.

First we cut the groups into pairs. If 1 and 2 hold, then the first group of each pair is a 1-group and the last pair is a singleton. Then we reduce this list of pairs by zipping them with componentwise addition. This means that the 1-groups and 0-groups are added separately. The addition preserves overflowing elements, so adding `[1,1,1]` and `[1,1]` gives `[2,2,1]`. Zipping does not, so if the last pair is a singleton, the componentwise sum of the 0-groups vanishes from the result. Finally, we check that all numbers in the result are equal to `n`.

```
ṠṘm(...)Q  First input is explicit, say 3, second is implicit.
        Q  List of slices.
  m(...)   Map this function (which counts good matches) over the slices
ṠṘ         and replicate each by the corresponding number.

F-m(...)mëhohttI  Count good matches. Argument is a slice, say [6,2,5].
         ë        Define a list of 4 functions:
          h        remove first element,
           oht     remove first and last element,
              t    remove last element,
               I   identity.
        m         Apply each: [[2,5],[2],[6,2],[6,2,5]]
  m(...)          Map function (which counts all matches): [0,0,1,2]
F-                Reduce by subtraction: 1
                  In Husk, - has reversed arguments, so this computes
                  M(x) - (M(tx) - (M(htx) - M(hx)))
                  where M means number of matches.

#(...)Qṁḋ  Count all matches. Argument is a slice.
       ṁ   Map and concatenate
        ḋ  binary expansions.
      Q    List of slices.
#(...)     Count number of truthy results of function (which recognizes a match).

ΛΛ=⁰Fzż+C2g  Recognize a match. Argument is list of bits, say [1,1,0,1,1,0,0,0,1,1].
          g  Group elements: [[1,1],[0],[1,1],[0,0,0],[1,1]]
        C2   Cut into pairs: [[[1,1],[0]],[[1,1],[0,0,0]],[[1,1]]]
    F        Reduce by
     z       zip (discarding extraneous elements) with
      ż      zip (preserving extraneous elements) with
       +     addition: [[3,3]]
Λ            For all lists
 Λ           all elements
  =⁰         are equal to first input.

```
> 5 votes

# Answer
# Perl 6, ~~114~~ ~~112~~ ~~110~~ ~~107~~ ~~106~~ 104 bytes

```
->\n,\L{L[map {[...] flat(^L Zxx(L>>.msb X+1))[.from,.to-1]},L.fmt('%b','')~~m:ov/(1+)<{"0+$0"x n-1}>/]}

```

Try it online!

### Explanation

```
->\n,\L{  # Anonymous block taking arguments n and L
 L[       # Return elements of L
   map {  # Map matches to ranges
    [...] # Create range from start/end pair
          # Map indices into binary string to indices into L
          flat(     # Flatten
               ^L   # indices into L
               Zxx  # repeated times
               (L>>.msb X+1)  # length of each binary representation
          )
          # Lookup start/end pair in map above
          [.from,.to-1]
   },
   L.fmt('%b','')  # Join binary representations
   ~~              # Regex match
   m:ov/(1+)<{"0+$0"x n-1}>/  # Find overlapping matches
 ]
}

```
> 7 votes

# Answer
# JavaScript (ES6), ~~187~~ ~~184~~ ~~177~~ 173 bytes

Takes input as `(n)(list)`. Returns an array of arrays.

```
n=>a=>(g=p=>(m=s.slice(p).match(`(1+)(0+\\1){${n-1}}`))?[a.filter((_,i)=>-~b[i-1]<p+m[0].length&b[i]>=p,p-=~m.index),...g(p)]:[])(s=[],b=a.map(n=>(s+=n.toString(2)).length))

```

Try it online!

### How?

We first compute the binary string \\$s\\$ and a list \\$b\\$ that describes the bounds of each number in \\$s\\$.

```
s = [], b = a.map(n => (s += n.toString(2)).length)

```

*Example:*

```
                      (0)     7     13
                       v      v     v
a = [109, 45] --> s = "1101101101101" --> b = [7, 13]
                       \_____/\____/
                         109    45

```

We use the following template to generate a regular expression matching binary fences:

```
`(1+)(0+\\1){${n-1}}`

```

This regular expression is applied to \\$s\\$, starting from a position \\$p\\$.

```
m = s.slice(p).match(`(1+)(0+\\1){${n-1}}`)

```

We start with \\$p=0\\$ and update it at each iteration according to the position of the previous match.

Whenever a match \\$m\\$ is found in \\$s\\$: for each \\$i\\$-th number in the input array, we test whether the interval made of its bounds (stored in \\$b\\$) overlaps the interval made of the starting and ending positions of \\$m\\$ in \\$s\\$.

```
a.filter((_, i) => -~b[i - 1] < p + m[0].length & b[i] >= p, p -= ~m.index)

```
> 4 votes

# Answer
# Python 2, ~~271~~ ~~246~~ ~~223~~ ~~214~~ ~~208~~ ~~202~~ ~~200~~ 195 bytes

```
lambda n,l,R=range,L=len:sum([next(([l[i:j+1]]for j in R(i,L(l))if re.match('(1+)'+r'(0+\1)'*~-n,('{:b}'*(1+j-i)).format(*l[i:])[o:])),[])for i in R(L(l))for o in R(L(bin(l[i]))-2)],[])
import re

```

Try it online!
> 3 votes

# Answer
# Python 2, 182 bytes

```
lambda n,L,b='{:b}'.format:[zip(*set([t
for t in enumerate(L)for _ in b(t[1])][slice(*m.span(1))]))[1]for
m in re.finditer('(?=((1+)'+r'[0]+\2'*~-n+'))',''.join(map(b,L)))]
import re

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~38~~ ~~36~~ 35 bytes

```
Œεy¨D¦y¦)bJεŒεγ0KDËsgIQyнyθP}}OÆFy,

```

Inspired by *@Zgarb*'s Husk answer.

Output the lists newline-delimited.

Try it online or verify all test cases.

**Explanation:**

```
Œ            # Get the sublists of the (implicit) input-list
 ε           # Loop `y` over each sublist:
             #  (implicitly push `y`)
  y¨         #  Push `y` with the last item removed
  D¦         #  Push `y` with the first and last items removed
  y¦         #  Push `y` with the first item removed
  )          #  Wrap all four into a list
   b         #  Get the binary-string of each integer
    J        #  Join each inner list together
     ε       #  Map each converted binary-string to:
      Œ      #   Get all substrings of the binary-string
      ε      #   Map each binary substring to:
       γ     #    Split it into chunks of equal adjacent digits
       0K    #    Remove all chunks consisting of 0s
       DË    #    Check if all chunks consisting of 1s are the same
       sgIQ  #    Check if the amount of chunks of 1s is equal to the second input-integer
       yн    #    Check if the substring starts with a 1
       yθ    #    Check if the substring end with a 1
       P     #    Check if all four checks above are truthy for this substring
             #    (1 if truthy; 0 if falsey)
     }}      #  Close both maps
       O     #  Take the sum of each inner list
        Æ    #  Reduce the list of sums by subtraction
         F   #  Loop that many times:
          y, #   And print the current sublist `y` with a trailing newline

```
> 0 votes

---
Tags: code-golf, number, binary, regular-expression
---


title: Compound Interest... with Wizard Money

text:
# Question
Title: Compound Interest... with Wizard Money
Gringotts isn't just a vault, but a reputable financial institution and wizards need loans too. Since you don't want to be screwed over by the Gringotts goblins, you decided it would be a good idea to write a program to calculate interest. Interest is compounded only yearly.

Your task is to calculate total owed amount after interest given the principal, interest rate, and time (whole years), operating in whole denominations of wizard money, rounding down to the nearest whole Knut. There are 29 Bronze Knuts in a Silver Sickle and 17 Sickles in a Gold Galleon.

## Example

```
Loan taken out:
 23 Knuts
 16 Sickles
103 Galleons
@ 7.250%
For 3 years

Total owed after interest:
 24 Knuts
  4 Sickles
128 Galleons

```

## Notes and Rules

* Input and output may be in any convenient format. You must take in Knuts, Sickles, Galleons, interest rate, and time. All but interest rate will be whole numbers. The interest rate is in increments of 0.125%.
* Input money is not guaranteed to be canonical (i.e. you can have 29 or more Knuts and 17 or more Sickles.)
* Output must be the canonical representation. (i.e. less than 29 Knuts and less than 17 Sickles)
* Totals owed, up to 1,000 Galleons, should be accurate to within 1 Knut per year of interest when compared with arbitrary precision calculations.
    + You may round down after each year of interest or only at the end. Reference calculations can take this into account for accuracy checks.

Happy golfing!

# Answer
# , ~~70~~ 62 bytes

```
function(d,i,y)(x=d%*%(a=c(1,29,493))*(1+i)^y)%/%a%%c(29,17,x)

```

Try it online!

Takes input as d: deposit in knuts, sickles, galleons; i: interest rate as decimal; y: years. Outputs final deposit in knuts, sickles, galleons. Thanks to @Giuseppe for using matrix multiplication to save some bytes (and pointing out how to avoid the need to wrap at 1e99).
> 6 votes

# Answer
# Python 3.8 (pre-release), ~~75~~ ~~74~~ 71 bytes

-1 bytes thanks to @EmbodimentofIgnorance
-3 bytes thanks to @xnor

This takes Knuts, Sickles, and Galleons as ints, interest as a float (decimal, not percentage), and years as an int. It returns a tuple containing the number after interest of Knuts, Sickles, and Galleons, respectively.

```
lambda K,S,G,R,Y:((k:=int((K+G*493+S*29)*(1+R)**Y))%29,k//29%17,k//493)

```

Usage:

```
>>> print(I(23,16,103,0.0725,3))
(24, 4, 128)

```

Try it online!
> 4 votes

# Answer
# APL+WIN, ~~37 28~~ 26 bytes

```
⌊a⊤((a←0 17 29)⊥⎕)×(1+⎕)*⎕

```

2 bytes saved thanks to lirtosiast

Try it online! Courtesy of Dyalog Classic

Explanation:

```
(1+⎕)*⎕ prompts for years followed by decimal interest rate and calculates
         compounding multiplier

((a←0 17 29)⊥⎕) prompts for Galleons, Sickles and Knuts and converts to Knuts

⌊a⊤ converts back to Galleons, Sickles and Knuts and floor
    after applying compound interest.

```
> 3 votes

# Answer
# Perl 6, 47 bytes

```
((1+*)*** *(*Z*1,29,493).sum+|0).polymod(29,17)

```

Try it online!

I'm surprised I managed to get this into an anonymous Whatever lambda! Especially the part where it's more `*`s than anything else. Takes input as `interest rate (e.g. 0.0725), years, [Knuts, Sickles, Galleons]` and returns a list of currencies in the same order.

### Explanation:

```
 (1+*)           # Add one to the interest rate
      ***        # Raise to the power of the year
          *      # And multiply by
           (*Z*1,29,493).sum      # The number of Knuts in the input
                            +|0   # And floor it
(                              ).polymod(29,17)   # Get the modulos after divmoding by 29 and 17

```
> 3 votes

# Answer
# Jelly, 29 bytes

```
“¢×ø‘©×\
÷ȷ2‘*⁵×÷¢S×¢d®U1¦Ṫ€Ḟ

```

A full program accepting arguments: `rate`; `[Galleons, Sickles, Knuts]`; `years`.
Prints `[Galleons, Sickles, Knuts]`.

**Try it online!**

Floors at the end of the entire term.
`÷ȷ2` may be removed if we may accept the rate as a ratio rather than a percentage.

### How?

```
“¢×ø‘©×\ - Link 1 multipliers: no arguments
“¢×ø‘    - list of code-age indices = [1,17,29]
     ©   - (copy this to the register for later use)
       \ - reduce by:
      ×  -   multiplication  = [1,17,493]

÷ȷ2‘*⁵×÷¢S×¢d®U1¦Ṫ€Ḟ - Main Link
 ȷ2                  - 10^2 = 100
÷                    - divide = rate/100
   ‘                 - increment = 1+rate/100
     ⁵               - 5th command line argument (3rd input) = years
    *                - exponentiate = (1+rate/100)^years --i.e. multiplicand
      ×              - multiply (by the borrowed amounts)
        ¢            - call last Link as a nilad
       ÷             - divide (all amounts in Galleons)
         S           - sum (total Galleons owed)
           ¢         - call last Link as a nilad
          ×          - multiply (total owed in each of Galleons, Sickles, Knuts)
             ®       - recall from register = [1,17,29]
            d        - divmod (vectorises) = [[G/1, G%1], [S/17, S^17], [K/17, K%17]]
              U1¦    - reverse first one = [[G%1, G/1], [S/17, S%17], [K/17, K%17]]
                 Ṫ€  - tail €ach = [G/1, S%17, K%17]
                   Ḟ - floor (vectorises)

```
> 2 votes

# Answer
# TI-BASIC (TI-84), ~~96~~ 90 Bytes

```
:SetUpEditor C:Ans→∟C:∟C(1)+29∟C(2)+493∟C(3)→T:T(1+∟C(4))^∟C(5)→T:remainder(iPart(T),493→R:{remainder(R,29),iPart(R/29),iPart(T/493)}

```

Input is `Ans`, a list with 5 items: Knuts, Sickles, Galleons, Interest (decimal), and Time (years).
Output is in `Ans` and is automatically printed out when the program completes.

**Un-golfed:**

```
:SetUpEditor C
:Ans→∟C
:∟C(1)+29∟C(2)+493∟C(3)→T
:T(1+∟C(4))^∟C(5)→T
:remainder(iPart(T),493→R
:{remainder(R,29),iPart(R/29),iPart(T/493)}

```

**Example:**

```
{32,2,5,0.05,5}
       {32 2 5 .05 5}
prgmCDGF1
            {12 10 6}

```

**Explanation:**

```
:SetUpEditor C
:Ans→∟C

```

A new list, `∟C`, is created and `Ans` is stored into it.

```
:∟C(1)+29∟C(2)+493∟C(3)→T

```

The Knuts, Sickles, and Galleons are converted into Knuts and stored into `T`.

```
:T(1+∟C(4))^∟C(5)→T

```

Takes the amount of Knuts and applies compound interest to it.
Interest is calculated here.

```
:remainder(iPart(T),493→R

```

Stores the **I**nteger **Part** of `T` modulo 493 into `R`. Used to shorten byte count.

```
:{remainder(R,29),iPart(R/29),iPart(T/493)}

```

Evaluates a list with 3 items (Knuts, Sickles, and Galleons). The list is automatically stored into `Ans`.

---

**Note:** Byte count is evaluated by taking the byte count given in **\[MEM\]****\[2\]****\[7\]** (program list in RAM) and subtracting the amount of characters in the program name and an extra 8 bytes used for the program:

103 - 5 - 8 = 90 bytes
> 2 votes

# Answer
# Intel 8087 FPU assembly, 86 bytes

```
d9e8 d906 7f01 dec1 8b0e 8301 d9e8 d8c9 e2fc df06 7901 df06 8701 df06
7b01 df06 8501 df06 7d01 dec9 dec1 dec9 dec1 dec9 9bd9 2e89 01df 0687
01df 0685 01d9 c1de c9d9 c2d9 f8d8 f2df 1e7b 01d8 fadf 1e7d 01d9 c9d9
f8df 1e79 01

```

Unassembled and documented:

```
; calculate P+I of loan from wizard
; input:
;   G: number of Galleons (mem16)
;   S: number of Sickles (mem16)
;   K: number of Knuts (mem16)
;   R: interest rate (float)
;   T: time in years (mem16)
;   GS: Galleons to Sickles exchange rate (mem16)
;   SK: Sickles to Knuts exchange rate (mem16)
; output:
;   G: number of Galleons (mem16)
;   S: number of Sickles (mem16)
;   K: number of Knuts (mem16)
WIZ_INT_CALC    MACRO   G, S, K, R, T, GS, SK
                LOCAL   LOOP_EXP
                    ; - calculate interet rate factor
    FLD1            ; load 1
    FLD   R         ; load interest rate
    FADD            ; ST = rate + 1
    MOV   CX, T     ; Exponent is count for loop
    FLD1            ; load 1 into ST as initial exponent value
LOOP_EXP:           ; loop calculate exponent
    FMUL  ST,ST(1)  ; multiply ST = ST * ST(1)
    LOOP  LOOP_EXP
                    ; - convert demonimations to Knuts
    FILD  K         ; load existing Knuts
    FILD  SK        ; load Sickles to Knuts rate
    FILD  S         ; load existing Sickles
    FILD  GS        ; load Galleons-to-Sickles exchange rate
    FILD  G         ; load existing Galleons
    FMUL            ; multiply galleons to get sickles
    FADD            ; add existing sickles
    FMUL            ; multiply sickles to get knuts
    FADD            ; add existing knuts
    FMUL            ; calculate P+I (P in Knuts * Interest factor)
                    ; - redistribute demonimations to canonical form
    FLDCW  FRD      ; put FPU in round-down mode
    FILD   SK       ; load Sickles to Knuts rate
    FILD   GS       ; load Galleons-to-Sickles exchange rate
    FLD    ST(1)    ; copy Galleons-to-Sickles exchange rate to stack for later
    FMUL            ; multiply to get Galleons-to-Knuts rate
    FLD    ST(2)    ; push original total Knuts from ST(2) into ST (lost by FPREM)
    FPREM           ; get remainder
    FDIV   ST,ST(2) ; divide remainder to get number of Sickles
    FISTP  S        ; store Sickles to S
    FDIVR  ST,ST(2) ; divide to get number of Galleons
    FISTP  G        ; store Galleons to G
    FXCH            ; swap ST, ST(1) for FPREM
    FPREM           ; get remainder to get number of Knuts
    FISTP  K        ; store Knuts to K
        ENDM

```

Implemented as a MACRO (basically a function), this is non-OS-specific machine-code using only the Intel 80x87 FPU / math co-processor for calculation.

Example test program with output:

```
    FINIT           ; reset FPU

    WIZ_INT_CALC    G,S,K,R,T,GS,SK     ; do the "Wizardy"

    MOV  AX, K      ; display Knuts
    CALL OUTDEC     ; generic decimal output routine
    CALL NL         ; CRLF

    MOV  AX, S      ; display Sickles
    CALL OUTDEC     ; generic decimal output routine
    CALL NL         ; CRLF

    MOV  AX, G      ; display Galleons
    CALL OUTDEC     ; generic decimal output routine
    CALL NL         ; CRLF

    RET             ; return to DOS

K   DW  23          ; initial Kunts
S   DW  16          ; initial Sickles
G   DW  103         ; initial Galleons
R   DD  0.0725      ; interest rate
T   DW  3           ; time (years)
GS  DW  17          ; Galleons to Sickles exchange rate
SK  DW  29          ; Sickles to Knuts exchange rate
FRD DW  177FH       ; 8087 control word to round down

```

***Output***
> 2 votes

# Answer
# Japt, 48 bytes

```
XÄ pY *(U*493+V*29+W)f
Uu493
[Uz493 ,Vz29 ,Vu29]

```

My first try at Japt, going for @Shaggy's bounty! Needless to say, this isn't very golfy :(

Try it Online!
> 1 votes

# Answer
# Haskell, 73 bytes

```
(g#s)k r n|(x,y)<-truncate((493*g+29*s+k)*(1+r)^n)%29=(x%17,y)
(%)=divMod

```

Try it online!

Thanks to @Laikoni for two bytes.

The dirty tricks: the number of coins in the input is floating point (`Double`), while the number of coins in the output is integral (`Integer`). The result is a nested pair `((Galleons, Sickles), Knotts)` to avoid having to flatten to a triple.

### Explanation

```
-- Define a binary operator # that
-- takes the number of Galleons
-- and Slivers and produces a
-- function taking the number of
-- Knots, the rate, and the
-- number of years and producing
-- the result.
(g#s) k r n
   -- Calculate the initial value
   -- in Knotts, calculate the
   -- final value in Knotts,
   -- and divide to get the number
   -- of Galleons and the
   -- remainder.
  |(x,y)<-truncate((493*g+29*s+k)*(1+r)^n)%29
  -- Calculate the number of Slivers
  -- and remaining Knotts.
  =(x%17,y)
(%)=divMod

```
> 1 votes

# Answer
# Stax, 24 bytes

```
»♀(╪M╢ú!!«ε◘÷╛SI►U/)-f!ö

```

Run and debug it

Input is space separated values. `interest years knuts sickles galleons`

Output is newline separated.

```
knuts
sickles
galleons

```
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 86 bytes

```
(a,b,c)=>((k=(int)((a.a*493+a.b*29+a.c)*Math.Pow(1+b,c)))/493,(k%=493)/29,k%29);int k;

```

Takes inout as a named tuple with 3 values representing knuts, sickles, and galleons, and interest rate as a double (not a percentage). I really wish C# had an exponentation operator. Math.Pow is way too long :(

Try it online!
> 0 votes

# Answer
# K, 46 Bytes

```
c:1000 17 29
t:{c\:{z(y*)/x}[c/:x;1+y%100;z]}

```

`c` store the list for base-conversion

`t` is the function that calculates total amount

Use example:

```
t[103 16 23;7.25;3]

```

writes `(128;4;24.29209)`

Explanation:

* `c/:x` transform the list (galleon; sickle; knuts) to kuts
* `1+y%100` calculate rate of interest (example 1.0725 for 7.25% rate)
* lambda `{z(y*)\x}` does the work: iterate 3 times, applying interes\*main, and returns final main.
* `c\:` generates galleon, sickles, knuts from knuts

NOTE.- if you don't need a names-function, we can use a lambda, saving 2 bytes `{c\:{z(y*)/x}[c/:x;1+y%100;z]}inputArgs`
> 0 votes

# Answer
## Batch, 171 bytes

```
@set i=%4
@set/af=0,i=8*%i:.=,f=%,f*=8
@set/ai+=%f:~,1%,k=%1*493+%2*29+%3
@for /l %%y in (1,1,%5)do @set/ak+=k*i/800
@set/ag=k/493,s=k/29%%17,k%%=29
@echo %g% %s% %k%

```

Takes input as command-line arguments in the order Galleons, Sickles, Knuts, interest, years. Interest is a percentage but expressed without the % sign. Truncates after every year. Output is in the order Galleons, Sickles, Knuts. Supports at least 5000 Galleons. Explanation:

```
@set i=%4
@set/af=0,i=8*%i:.=,f=%,f*=8

```

Batch only has integer arithmetic. Fortunately, the interest rate is always a multiple of `0.125`. We start by splitting on the decimal point, so that `i` becomes the integer part of the interest rate and `f` the decimal fraction. These are then multiplied by 8. The first digit of `f` is now the number of eighths in the percentage interest rate.

```
@set/ai+=%f:~,1%,k=%1*493+%2*29+%3

```

This is then extracted using string slicing and added on to give an interest rate in 1/800ths. The number of Knuts is also calculated.

```
@for /l %%y in (1,1,%5)do @set/ak+=k*i/800

```

Calculate and add on each year's interest.

```
@set/ag=k/493,s=k/29%%17,k%%=29
@echo %g% %s% %k%

```

Convert back to Galleons and Sickles.
> 0 votes

# Answer
# 05AB1E (legacy), 24 bytes

```
>Im•1ýÑ•3L£I*O*ï29‰ć17‰ì

```

Port of *@JoKing*'s Perl 6 answer, so make sure to upvote him as well if you like this answer!

I'm using the legacy version due to a bug in the new version where `£` doesn't work on integers, so an explicit cast to string `§` (between the second  and `3`) is required (until the bug is fixed).

Takes the interest as decimal, followed by the year, followed by the list of \[Knuts, Sickles, Galleons\].

Try it online.

**Explanation:**

```
>                      # Increase the (implicit) interest decimal by 1
                       #  i.e. 0.0725 → 1.0725
 Im                    # Take this to the power of the year input
                       #  i.e. 1.0725 and 3 → 1.233...
•1ýÑ•                  # Push compressed integer 119493
     3L                # Push list [1,2,3]
       £               # Split the integer into parts of that size: [1,19,493]
        I*             # Multiply it with the input-list
                       #  i.e. [1,19,493] * [23,16,103] → [23,464,50779]
          O            # Take the sum of this list
                       #  i.e. [23,464,50779] → 51266
           *           # Multiply it by the earlier calculated number
                       #  i.e. 51266 * 1.233... → 63244.292...
            ï          # Cast to integer, truncating the decimal values
                       #  i.e. 63244.292... → 63244
             29‰       # Take the divmod 29
                       #  i.e. 63244 → [2180,24]
                ć      # Extract the head; pushing the remainder-list and head separately
                       #  i.e. [2180,24] → [24] and 2180
                 17‰   # Take the divmod 17 on this head
                       #  i.e. 2180 → [128,4]
                    ì  # And prepend this list in front of the remainder-list
                       #  i.e. [24] and [128,4] → [128,4,24]
                       # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•1ýÑ•` is `119493`.
> 0 votes

# Answer
# APL(NARS), 37 char, 74 bytes

```
{(x y z)←⍵⋄⌊¨a⊤(z⊥⍨a←0 17 29)×x*⍨1+y}

```

translation of the very good and very few bytes APL solution by Graham user to a solution that use one function instead of standard input... test and how to use it:

```
  f←{(x y z)←⍵⋄⌊¨a⊤(z⊥⍨a←0 17 29)×x*⍨1+y}
  f 3 0.0725 (103 16 23)
128 4 24

```

(i don't say i had understood algorithm)
> 0 votes

# Answer
# Perl 5, 70 bytes

```
$,=$";say 0|($_=(<>+<>*29+<>*493)*(1+<>)**<>)/493,0|($_%=493)/29,$_%29

```

Try it online!
> 0 votes

---
Tags: code-golf, math
---


# Question
Title: Is it possible to make a clamp function shorter than a ternary in JS?
Imagine this short function to clamp a number between 0 and 255:

```
c = n => n > 0 ? n < 255 ? n : 255 : 0

```

Is this the shortest possible version of a clamp function with JavaScript (without ES.Next features)?

P.S: Not sure if it's relevant but, the 0 and 255 are not random, the idea is to clamp a number as an 8-bit unsigned integer.

# Answer
> 25 votes
# 20 bytes

For reference, this is the original version without whitespace and without naming the function:

```
n=>n>0?n<255?n:255:0

```

Try it online!

---

# 19 bytes

We can save a byte by inverting the logic of the ternary tests and using `n>>8` to test whether \\$n\\$ is greater than \\$255\\$. Because of the bitwise operation, this will however fail for \\$n\ge 2^{32}\\$.

```
n=>n<0?0:n>>8?255:n

```

Try it online!

---

# 19 bytes

This one returns \\$false\\$ instead of \\$0\\$ but works for \\$n\ge 2^{32}\\$.

```
n=>n>255?255:n>0&&n

```

Try it online!

---

# 18 bytes

By combining both versions above, we end up with a function that works for \\$256-2^{32}\le n\<2^{32}\\$ and returns \\$false\\$ for \\$n\<0\\$.

```
n=>n>>8?n>0&&255:n

```

Try it online!

### Commented

```
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    n > 0 &&  //   return false if n is negative
    255       //   or 255 otherwise
  :           // else:
    n         //   return n unchanged

```

(This is a fixed revision of the code proposed by @ValueInk in the comments.)

---

# 17 bytes

We can go a step further by limiting the valid input range to \\$-2^{24}\< n\le 2^{24}\\$:

```
n=>n>>8?-n>>>24:n

```

Try it online!

### Commented

```
n =>          // n = input number
  n >> 8 ?    // if n is greater than 255 or n is negative:
    -n >>> 24 //   non-arithmetic right-shift of -n by 24 positions
  :           // else:
    n         //   return n unchanged

```

---
Tags: code-golf, math, tips, javascript
---


title: Unique Brick Tilings Within A Rectangle

text:
# Question
Title: Unique Brick Tilings Within A Rectangle
I was browsing Stackoverflow and saw this question about tiling an MxN rectangle, and I thought it would be great for golfing. Here is the task.

Given the dimension M and N, write a program that outputs how many unique ways a MxN rectangle (N is the number of rows, not columns. Not that it really matters) can be tiled given these constraints.

1. All tiles are 2x1 or 3x1
2. All tiles stay within their row (ie they are all horizontal)
3. Between every two adjacent rows tiles should not be aligned, except on the two ends
4. M and N are guaranteed to be at least 1

For example, a valid tiling of a 8x3 matrix would be

```
  2    3     3
  |    |     |
  v    v     v
 _______________
|___|_____|_____|
|_____|_____|___|
|___|_____|_____|

```

But the following would be invalid, because the rows align

```
  2    3     3
  |    |     |
  v    v     v
 _______________
|___|_____|_____|
|_____|___|_____|
|_____|_____|___|

```

Test cases:

8x3: 4

3x1: 1

1x1: 0

9x4: 10

Code golf, so shortest answer wins.

# Answer
# Jelly, 20 bytes

```
2*ḃ€2‘ÄṪ⁼¥Ƈ⁸ṗfƝẸ$€ċ0

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6),  ~~119 110 106 96~~  91 bytes

Takes input as \\$(N,M)\\$.

```
f=(n,m,p=0,g=(w,h=x=>g(p[g[w-=x]=1,w]||w)*g[w]--)=>w>3?h(2)+h(1):w>1&&f(n,m-1,g))=>m?g(n):1

```

Try it online!

### Commented

*NB: This code uses 3 different functions that call each other. This makes it a bit difficult to keep track of the scope of the variables. Keep in mind that \\$g\\$ is defined within the scope of \\$f\\$ and \\$h\\$ is defined within the scope of \\$g\\$.*

```
f = (                    // f is a recursive function taking:
  n,                     //   n = number of columns
  m,                     //   m = number of rows
  p = 0,                 //   p = object holding the previous row
  g = (                  //   g = recursive function taking:
    w,                   //     w = remaining width that needs to be filled in the
                         //         current row
    h = x =>             //     h = helper function taking x
                         // h body:
      g(                 //   recursive call to g:
        p[g[w -= x] = 1, //     subtract either 2 or 1 from w and mark this width as used
          w              //     test p[w]
        ]                //     pass p[w] if p[w] = 1 (which will force the next iteration
                         //     to fail immediately)
        || w             //     otherwise, pass w
      )                  //   end of recursive call
      * g[w]--           //   then restore g[w] to 0
  ) =>                   // g body:
    w > 3 ?              //   if w > 3, we need to insert at least 2 more bricks:
      h(2) + h(1)        //     invoke h with x = 2 and x = 1
    :                    //   else:
      w > 1              //     this is the last brick; we just check if it can be inserted
      &&                 //     abort if w is equal to 1 (a brick does not fit in there)
      f(                 //     otherwise, do a recursive call to f:
        n,               //       n is unchanged
        m - 1,           //       decrement m
        g                //       pass g as the new reference row
      )                  //     end of recursive call
) =>                     // f body:
  m ? g(n) : 1           //   yield 1 if we made it to the last row or call g otherwise

```
> 4 votes

# Answer
# , ~~243~~ 231 bytes

```
function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=Map)`if`(m<2,0,sum((e=eigen(lengths(outer(p<-unlist(M(M,list(function(x,y)cumsum(2+1:y%in%x)),M(combn,j,i,s=F),j),F),p,Vectorize(intersect)))<2))$ve%*%diag(e$va^(n-1))%*%solve(e$ve)))

```

Try it online!

Version with line breaks:

```
function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=Map)`if`(m<2,0,
sum((e=eigen(lengths(outer(p<-unlist(M(M,list(function(x,y)cumsum(2+1:y%in%x)),
M(combn,j,i,s=F),j),F),p,Vectorize(intersect)))<2))$ve%*%diag(e$va^(n-1))%*%solve(e$ve)))

```

Note no recursion, and handles fairly large values of m and n (e.g. 24x20 -\> 3.3e19)

Here's a commented answer that works more or less the same as the above, but I've unnested all of the functions so it's actually readable:

```
f <- function(m,n) {
  # First work out what potential combinations of 2s and 3s add up to m
  i <- 2*0:(m %/% 6) + m %% 2 # Vector with numbers of possible 3s
  j <- i + (m - 3 * i) / 2 # Vector with total number of 2s and 3s
  if (m < 2) {
    0 # If wall less than 2 wide, no point in continuing because answer is 0
  } else {
    # Work out all possible positions of threes for each set
    positions_of_threes <- Map(combn, j, i, simplify = FALSE)
    # Function to work out the cumulative distance along the wall for a given
    # Set of three positions and number of bricks
    make_cumulative_bricks <- function(pos_threes, n_bricks) {
      bricks <- 1:n_bricks %in% pos_threes
      cumsum(2 + bricks)
    }
    # Find all possible rows with cumulative width of wall
    # Note because this is a `Map` with depth two that needs to be vectorised
    # for both `positions_of_threes` and `j`, and we're using base R, the
    # function `make_cumulative_bricks` needs to be placed in a list
    cum_bricks <- Map(Map, list(make_cumulative_bricks), positions_of_threes, j)
    # Finally we have the list of possible rows of bricks as a flat list
    cum_bricks_unlisted <- unlist(cum_bricks, recursive = FALSE)
    # Vectorise the intersect function
    intersect_v <- Vectorize(intersect, SIMPLIFY = FALSE)
    # Find the length of all possible intersects between rows
    intersections <- outer(cum_bricks_unlisted, cum_bricks_unlisted, intersect_v)
    n_intersections <- lengths(intersections)
    # The ones not lined up will only have a single intersect at `m`
    not_lined_up <- n_intersections == 1
    # Now use method described at https://stackoverflow.com/a/9459540/4998761
    # to calculate the (matrix of TRUE/FALSE for lined-up) to the power of `n`
    eigen_nlu <- eigen(not_lined_up)
    final_mat <- eigen_nlu$vectors %*%
      diag(eigen_nlu$values ^ (n - 1)) %*%
      solve(eigen_nlu$vectors)
    # The sum of this matrix is what we're looking for
    sum(final_mat)
  }
}
f(20,20)

```

The method for taking a matrix and repeatedly multiplying it by itself is from a question on stackoverflow. This approach works here because it effectively calculates the cumulative number of branches through the different possible rows of bricks.

If external packages are allowed, I can get it down to 192:

```
function(m,n,i=2*0:(m%/%6)+m%%2,j=i+(m-3*i)/2,M=purrr::map2)`if`(m<2,0,sum(expm::`%^%`(lengths(outer(p<-unlist(M(M(j,i,combn,s=F),j,M,~cumsum(2+1:.y%in%.)),F),p,Vectorize(intersect)))<2,n-1)))

```
> 1 votes

# Answer
# Jelly, 26 bytes

```
2*ḃ€2‘ÄṪ⁼¥Ƈ⁸œ&L¬ɗþ`æ*⁴’¤SS

```

Try it online!

## Broken down:

Generate a list of possible walls as cumulative sums with the end removed:

```
2*ḃ€2‘ÄṪ⁼¥Ƈ⁸

```

Find the outer table of all possible walls against each other that don’t have any intersections:

```
œ&L¬ɗþ`

```

Take this matrix to the power of (N-1) and then sum it all up:

```
æ*⁴’¤SS

```

Uses the first bit from @EriktheOutgolfer’s answer to generate the list of possible walls, and then uses the matrix intersection and matrix exponentiation approach from my R answer. As such, it works well even with large N. This is my first Jelly answer, and I suspect it can be golfed more. I’d also ideally like to change the first section so that the time and memory requirements don’t scale exponentially with M.
> 1 votes

# Answer
# 05AB1E, 42 bytes

```
Åœʒ23yåP}€œ€`Ùε.¥¦¨}IиI.ÆÙεøyíø‚€€üQOO_P}O

```

I'm almost too ashamed to post this, and it can definitely be golfed by A LOT with a different approach, but since it took a while to complete I decided to post it anyway and golf it down from here. The challenge looks easier than it is imo, but I'm definitely using a wrong approach here and I have the feeling 05AB1E could do around 25 bytes..

Try it online. NOTE: Not only is it long, it's also inefficient, since the `9x4` test case runs in about 40 seconds on TIO..

**Explanation:**

```
Åœ             # Get all possible ways to sum to the (first) implicit input
               #  i.e. 8 → [[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,2],[1,1,1,1,1,3],[1,1,1,1,2,2],[1,1,1,1,4],[1,1,1,2,3],[1,1,1,5],[1,1,2,2,2],[1,1,2,4],[1,1,3,3],[1,1,6],[1,2,2,3],[1,2,5],[1,3,4],[1,7],[2,2,2,2],[2,2,4],[2,3,3],[2,6],[3,5],[4,4],[8]]
  ʒ23yåP}      # Only leave those consisting of 2s and/or 3s
               #  → [[2,2,2,2],[2,3,3]]
         €œ    # For each: get all permutations
           €`  # Flatten this list of lists once
             Ù # And uniquify it (leaving all possible distinct rows of bricks)
               #  → [[2,2,2,2],[3,3,2],[3,2,3],[2,3,3]]
ε    }         # For each:
 .¥            #  Get the cumulative sum
   ¦¨          #  With the leading 0 and trailing first input removed
               #   → [[2,4,6],[3,6],[3,5],[2,5]]
      Iи       # Repeat this list the second input amount of times
               #  i.e. 3 → [[2,4,6],[3,6],[3,5],[2,5],[2,4,6],[3,6],[3,5],[2,5],[2,4,6],[3,6],[3,5],[2,5]]
        I.Æ    # Get all combinations of lists the size of the second input
           Ù   # And uniquify the result (leaving all possible distinct walls)
               #  → [[[2,4,6],[3,6],[3,5]],[[2,4,6],[3,6],[2,5]],[[2,4,6],[3,6],[2,4,6]],[[2,4,6],[3,6],[3,6]],[[2,4,6],[3,5],[2,5]],[[2,4,6],[3,5],[2,4,6]],[[2,4,6],[3,5],[3,6]],[[2,4,6],[3,5],[3,5]],[[2,4,6],[2,5],[2,4,6]],[[2,4,6],[2,5],[3,6]],[[2,4,6],[2,5],[3,5]],[[2,4,6],[2,5],[2,5]],[[2,4,6],[2,4,6],[3,6]],[[2,4,6],[2,4,6],[3,5]],[[2,4,6],[2,4,6],[2,5]],[[2,4,6],[2,4,6],[2,4,6]],[[3,6],[3,5],[2,5]],[[3,6],[3,5],[2,4,6]],[[3,6],[3,5],[3,6]],[[3,6],[3,5],[3,5]],[[3,6],[2,5],[2,4,6]],[[3,6],[2,5],[3,6]],[[3,6],[2,5],[3,5]],[[3,6],[2,5],[2,5]],[[3,6],[2,4,6],[3,6]],[[3,6],[2,4,6],[3,5]],[[3,6],[2,4,6],[2,5]],[[3,6],[2,4,6],[2,4,6]],[[3,6],[3,6],[3,5]],[[3,6],[3,6],[2,5]],[[3,6],[3,6],[2,4,6]],[[3,6],[3,6],[3,6]],[[3,5],[2,5],[2,4,6]],[[3,5],[2,5],[3,6]],[[3,5],[2,5],[3,5]],[[3,5],[2,5],[2,5]],[[3,5],[2,4,6],[3,6]],[[3,5],[2,4,6],[3,5]],[[3,5],[2,4,6],[2,5]],[[3,5],[2,4,6],[2,4,6]],[[3,5],[3,6],[3,5]],[[3,5],[3,6],[2,5]],[[3,5],[3,6],[2,4,6]],[[3,5],[3,6],[3,6]],[[3,5],[3,5],[2,5]],[[3,5],[3,5],[2,4,6]],[[3,5],[3,5],[3,6]],[[3,5],[3,5],[3,5]],[[2,5],[2,4,6],[3,6]],[[2,5],[2,4,6],[3,5]],[[2,5],[2,4,6],[2,5]],[[2,5],[2,4,6],[2,4,6]],[[2,5],[3,6],[3,5]],[[2,5],[3,6],[2,5]],[[2,5],[3,6],[2,4,6]],[[2,5],[3,6],[3,6]],[[2,5],[3,5],[2,5]],[[2,5],[3,5],[2,4,6]],[[2,5],[3,5],[3,6]],[[2,5],[3,5],[3,5]],[[2,5],[2,5],[2,4,6]],[[2,5],[2,5],[3,6]],[[2,5],[2,5],[3,5]],[[2,5],[2,5],[2,5]]]
ε              # Map all walls `y` to:
 ø             #  Zip/transpose; swapping rows and columns
 yí            #  Reverse each row in a wall `y`
   ø           #  Also zip/transpose those; swapping rows and columns
 ‚             #  Pair both
  €            #  For both:
   €           #   For each column:
    ü          #    For each pair of bricks in a column:
     Q         #     Check if they are equal to each other (1 if truthy; 0 if falsey)
    O          #    Then take the sum of these checked pairs for each column
   O           #   Take the sum of that entire column
   _           #   Then check which sums are exactly 0 (1 if 0; 0 if anything else)
   P           #   And check for which walls this is only truthy by taking the product
}O             # After the map: sum the resulting list
               # (and output it implicitly as result)

```
> 0 votes

# Answer
# Charcoal, 89 bytes

```
Ｎθ⊞υ⟦⟧≔⟦⟧ηＦυＦ⟦²¦³⟧«≧⁺∧Ｌι§ι⁰κ¿⁼κθ⊞ηι¿‹κθ⊞υ⁺⟦κ⟧ι»≔Ｅη⟦ι⟧ζＦ⊖Ｎ«≔ζι≔⟦⟧ζＦιＦη¿¬⊙§κ⁰№λμ⊞ζ⁺⟦λ⟧κ»ＩＬζ

```

Try it online! Link is to verbose version of code. Works for rectangles of size up to about 12 on TIO, but could be made about three times faster at a cost of 2 bytes by using bit twiddling instead of list intersection. Explanation:

```
Ｎθ

```

Input the width.

```
⊞υ⟦⟧

```

Start with a row with no bricks.

```
≔⟦⟧η

```

Start with no completed rows.

```
Ｆυ

```

Loop over the rows.

```
Ｆ⟦²¦³⟧«

```

Loop over the bricks.

```
≧⁺∧Ｌι§ι⁰κ

```

Add the brick width to the current row width.

```
¿⁼κθ⊞ηι

```

If this results in the input width then add this row to the list of completed rows.

```
¿‹κθ⊞υ⁺⟦κ⟧ι»

```

Otherwise if this is still less than the input width then add the new row to the list of rows, thus causing it to be picked up by a later iteration.

```
≔Ｅη⟦ι⟧ζ

```

Make a list of walls of one row.

```
Ｆ⊖Ｎ«

```

Loop over one less than the height.

```
≔ζι

```

Save the list of walls.

```
≔⟦⟧ζ

```

Clear the list of walls.

```
Ｆι

```

Loop over the saved list of walls.

```
Ｆη

```

Loop over the completed rows.

```
¿¬⊙§κ⁰№λμ⊞ζ⁺⟦λ⟧κ»

```

If the row can be added to this wall then add that to the list of walls.

```
ＩＬζ

```

Output the length of the final list of walls.
> 0 votes

---
Tags: code-golf, combinatorics, permutations
---