title: The "Do While False" idiom

text:
# Question
Title: The "Do While False" idiom
# Do While False

At work today one of my colleagues was describing the use-case for do while(false). The person he was talking to thought that this was silly and that simple if statements would be much better. We then proceeded to waste half of our day discussing the best manner to write something equivalent to:

```
do
{
   //some code that should always execute...

   if ( condition )
   {
      //do some stuff
      break;
   }

   //some code that should execute if condition is not true

   if ( condition2 )
   {
       //do some more stuff
       break;
   }

   //further code that should not execute if condition or condition2 are true

}
while(false);

```

This is an idiom which is found in c quite often. Your program should produce the same output as the below pseudo-code depending on the conditions.

```
do
{
   result += "A";

   if ( C1)
   {
      result += "B";
      break;
   }

   result += "C"

   if ( C2 )
   {
       result += "D";
       break;
   }

   result += "E";

}
while(false);

print(result);

```

Therefore the input could be:

```
1. C1 = true, C2 = true
2. C1 = true, C2 = false
3. C1 = false, C2 = true
4. C1 = false, C2 = false

```

and the output should be:

```
1. "AB"
2. "AB"
3. "ACD"
4. "ACE"

```

This is code-golf so answers will be judged on bytes. Standard loopholes are banned.

Yes this is a simple one, but hopefully we will see some creative answers, I'm hoping the simplicity will encourage people to use languages they are less confident with.

# Answer
# Python 3, 31

Saved 1 byte thanks to xnor.

Only one byte away from ES6. :/ Stupid Python and its long anonymous function syntax.

Hooray for one liners!

```
lambda x,y:x*"AB"or"AC"+"ED"[y]

```

Test cases:

```
assert f(1, 1) == "AB"
assert f(1, 0) == "AB"
assert f(0, 1) == "ACD"
assert f(0, 0) == "ACE"

```
> 18 votes

# Answer
# JavaScript ES6, ~~30~~ ~~26~~ 25 bytes

A simple anonymous function taking two inputs. Assign to a variable to call. **Update**: Let's jump on the index bandwagon. It saves 4 bytes. *I have secured my lead over Python*. Saved a byte by currying the function; call like `(...)(a)(b)`. Thanks Patrick Roberts!

```
a=>b=>a?"AB":"AC"+"ED"[b]

```

Old, original version, 30 bytes (included to not melt into the python answer `(;`):

```
(a,b)=>"A"+(a?"B":b?"CD":"CE")

```
> 13 votes

# Answer
# C preprocessor macro, 34

* 1 byte saved thanks to @TobySpeight

```
#define f(a,b)a?"AB":b?"ACD":"ACE"

```

Try it online.
> 13 votes

# Answer
# MATL, 15 ~~17~~ bytes

```
?'AB'}'AC'69i-h

```

Inputs are `0` or `1` on separate lines. Alternatively, `0` can be replaced by `F` (MATL's `false`) and `1` by `T` (MATL's `true`).

**Try it online!**

```
?           % if C1 (implicit input)
  'AB'      %   push 'AB'
}           % else
  'AC'      %   push 'AC'
  69        %   push 69 ('E')
  i-        %   subtract input. If 1 gives 'D', if 0 leaves 'E'
  h         %   concatenate horizontally
            % end if (implicit)

```
> 9 votes

# Answer
## Haskell, 28 bytes

```
x#y|x="AB"|y="ACD"|1<2="ACE"

```

Usage example: `False # True` -\> `"ACD"`.

Using the input values directly as guards.
> 9 votes

# Answer
## Brainfuck, 65 bytes

This assumes that C1 and C2 are input as raw 0 or 1 bytes. e.g.

```
echo -en '\x00\x01' | bf foo.bf

```

Golfed:

```
++++++++[>++++++++<-]>+.+>+>,[<-<.>>-]<[<+.+>>,[<-<.>>-]<[<+.>-]]

```

Ungolfed:

```
                                      Tape
                                      _0
++++++++[>++++++++<-]>+.+  print A    0 _B
>+>,                       read C1    0 B 1 _0  or  0 B 1 _1
[<-<.>>-]<                 print B    0 B _0 0  or  0 B _1 0
[<+.+>>                    print C    0 D 1 _0
    ,                      read C2    0 D 1 _0  or  0 D 1 _1
    [<-<.>>-]<             print D    0 D _0 0  or  0 D _1 0
    [<+.>-]                print E    0 D _0    or  0 E _0
]

```

I believe it worth noting that this solution *is* in fact based on breaking out of while loops.
> 9 votes

# Answer
# GNU Sed, 21

```
/^1/cAB
/1$/cACD
cACE

```

Ideone.
> 7 votes

# Answer
# NTFJ, 110 bytes

```
##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@*):~||(~#~~~#~#@*)

```

More readable:

```
##~~~~~#@|########@|~#~~~~~#@*(~#~~~~#~@*########@^)~#~~~~##@*##~~~~~#@|########@|(~#~~~#~~@*
):~||(~#~~~#~#@*)

```

That was certainly entertaining. Try it out here, using two characters (`0` or `1`) as input.

Using ETHProduction's method for converting to 0, 1 (characters) to bits, this becomes simpler.

```
##~~~~~#@|########@|

```

This is the said method. Pushing 193 (`##~~~~~#@`), NANDing it (`|`) with the top input value (in this case, the first char code, a 48 or 49). This yields 254 for 1 and 255 for 0. NANDing it with 255 (`########@`) yields a 0 or 1 bit according to the input.

```
~#~~~~~#@*

```

This prints an `A`, since all input begins with `A`. `*` pops the `A` when printing, so the stack is unchanged from its previous state.

```
(~#~~~~#~@*########@^)

```

Case 1: the first bit is `1`, and `(` activates the code inside. `~#~~~~#~@*` prints `B`, and `########@^` pushes 255 and jumps to that position in the code. This being the end of the program, it terminates.

Case 2: the first bit is `0`. `(` skips to `)` and the code continues.

```
~#~~~~##@*

```

This prints a `C`, because that's the next character.

```
##~~~~~#@|########@|

```

This converts our second input to a bit.

```
(~#~~~#~~@*)

```

If our second bit is a 1, we proceed to print an `E`.

```
:~||

```

This is the NAND representation of the Boolean negation of our bit: `A NAND (0 NAND A) = NOT A`.

```
(~#~~~#~#@*)

```

This now activates if the bit was a `0`, and prints `E`.
> 7 votes

# Answer
# Pyth, 16 bytes

```
+\A?Q\B+\C?E\D\E

```

Test suite

Ternaries!

Explanation:

```
+\A              Start with an A
?Q\B             If the first variable is true, add a B and break.
+\C              Otherwise, add a C and
?E\D             If the second variable is true, add a D and break.
\E               Otherwise, add a E and finish.

```

Input on two consecutive lines.
> 5 votes

# Answer
## Pyth, 13 chars, 19 bytes

```
.HC@"૎્««"iQ2

```

Takes input in form \[a,b\]

Explanation

```
               - autoassign Q = eval(input())
           iQ2 -    from_base(Q, 2) - convert to an int
   @"૎્««"    -   "૎્««"[^]
  C            -  ord(^)
.H             - hex(^)

```

Try it here

Or use a test suite
> 5 votes

# Answer
# CJam, 15 ~~16~~ ~~17~~ bytes

```
'Ali'B'C'Eli-+?

```

**Try it online!**

*One byte off thanks to @randomra, and one byte off thanks to @Dennis*

Explanation:

```
'A                  e# push "A"
  li                e# read first input as an integer
    'B              e# push "B"
      'C            e# push "C"
        'E          e# push "E"
          li-       e# leave "E" or change to "D" according to second input
             +      e# concatenate "C" with "E" or "D"
              ?     e# select "B" or "C..." according to first input

```

---

Old version (16 bytes):

```
'Ali'B{'C'Eli-}?

```

Explanation:

```
'A                  e# push character "A"
               ?    e# if-then-else
  li                e# read first input as an integer. Condition for if
    'B              e# push character "B" if first input is true
      {       }     e# execute this if first input is false
       'C           e# push character "C"
         'E         e# push character "E"
           li       e# read second input as an integer
             -      e# subtract: transform "E" to "D" if second input is true
                    e# implicitly display stack contents

```
> 5 votes

# Answer
# C, 76 bytes

I renamed `c1` to `c`, `c2` to `C` and `result` to `r`. C programmers go to extremes to avoid `goto`. If you ever have a problum with absurd syntax in C, it is most likely to be because you did not use `goto`.

```
char r[4]="A";if(c){r[1]=66;goto e;}r[1]=67;if(C){r[2]=68;goto e;}r[2]=69;e:

```

### Ungolfed

```
char r[4] = "A";
if(c1){
    r[1] = 'B';
    goto end;
}
r[1] = 'C';
if(c2){
    r[2] = 'D';
    goto end;
}
r[2] = 'E';
end:

```
> 4 votes

# Answer
## C, 41 bytes

I'm not sure if the question requires a program, a function or a code snippet.
Here's a function:

```
f(a,b){a=a?16961:4473665|b<<16;puts(&a);}

```

It gets the input in two parameters, which must be 0 or 1 (well, `b` must), and prints to stdout.

Sets `a` to one of `0x4241`, `0x454341` or `0x444341`. When printed as a string, on a little-endian ASCII system, gives the required output.
> 4 votes

# Answer
# , ~~41~~ ~~39~~ 37 bytes

```
pryr::f(c("ACD","ACE","AB")[1+a+a^b])

```

Try it online!

In R, `TRUE` and `FALSE` are coerced to `1` and `0` respectively when you attempt to use them as numbers. We can convert these numbers to indices `1`, `2`, and `3` through the formula `1+a+a^b`.

```
  a  |   b  | 1+a+a^b
TRUE | TRUE | 1+1+1^1 = 3
TRUE | FALSE| 1+1+1^0 = 3
FALSE| TRUE | 1+0+0^1 = 1
FALSE| FALSE| 1+0+0^0 = 2

```

These values are then used to index the list `ACD`, `ACE`, `AB` to yield the correct output.

Saved two bytes thanks to JayCe.

If instead you prefer a version with an `if` statement, there's the following for 41 bytes:

```
pryr::f(`if`(a,"AB",`if`(b,"ACD","ACE")))

```

Try it online!
> 4 votes

# Answer
# Mathematica, ~~35~~ 30 bytes

```
If[#,"AB",If[#2,"ACD","ACE"]]&

```

Very simple. Anonymous function.
> 3 votes

# Answer
# JavaScript, 38 bytes

Use no-delimiter `0` or `1` instead of `false`/`true`

```
_=>"ACE ACD AB AB".split` `[+('0b'+_)]

```
> 3 votes

# Answer
## Retina, 22 bytes

```
1.+
AB
.+1
ACD
.+0
ACE

```

Try it Online
> 3 votes

# Answer
## **Caché ObjectScript**, 27 bytes

```
"A"_$s(x:"B",y:"CD",1:"CE")

```
> 3 votes

# Answer
# ArnoldC, 423 bytes

```
IT'S SHOWTIME
HEY CHRISTMAS TREE a
YOU SET US UP 0
HEY CHRISTMAS TREE b
YOU SET US UP 0
BECAUSE I'M GOING TO SAY PLEASE a
BECAUSE I'M GOING TO SAY PLEASE b
TALK TO THE HAND "ABD"
BULLSHIT
TALK TO THE HAND "ABE"
YOU HAVE NO RESPECT FOR LOGIC
BULLSHIT
BECAUSE I'M GOING TO SAY PLEASE b
TALK TO THE HAND "ACD"
BULLSHIT
TALK TO THE HAND "ACE"
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE NO RESPECT FOR LOGIC
YOU HAVE BEEN TERMINATED

```

Since ArnoldC doesn't seem to have formal input, just change the first 2 `YOU SET US UP` values to either 0 or 1 instead.

# Explanation

This is just a whole bunch of conditional statements which account for all the possible outputs. Why, you may ask? Well, ArnoldC doesn't really have string comprehension. It can't even concatenate strings! As a result, we have to resort to the more... inefficient... method.
> 3 votes

# Answer
# Java, 28 bytes

Same boilerplate as a lot of the answers. type is `BiFunction<Boolean,Boolean, String>`.

```
(c,d)->c?"AB":d?"ACD":"ACE"

```
> 3 votes

# Answer
# Pyth, 21 bytes

```
@c"ACE ACD AB AB"diz2

```

Try it here!

Input is taken as 0 or 1 instead of true/false while C1 comes first.

## Explanation

Just using the fact that there are only 4 possible results. Works by interpreting the input as binary, converting it to base 10 and using this to choose the right result from the lookup string.

```
@c"ACE ACD AB AB"diz2   # z= input

                  iz2   # Convert binary input to base 10
 c"ACE ACD AB AB"d      # Split string at spaces
@                       # Get the element at the index

```
> 2 votes

# Answer
# , 20 bytes

In the event that the first input is one, only one input is taken. I assume that this behaviour is allowed. Try it here!

```
'B'AjhMr$'C'E@j-#rCp

```

Ungolfed:

```
'B'A jh M
   r$ 'C 'E@ j - # r
 C p

```

Explained:

```
'B'A

```

This pushes the characters `B` then `A` to the stack.

```
jh M

```

This takes one input, increments it, pops it and moves over that number of sections.

Case 1: `j1 = 0`. This is the more interesting one. `r$` reverses the stack and pops a value, `'C'E` pushes characters `C` and `E`. `@` converts `E` to its numeric counterpart, subtracts the second input from it, and reconverts it to a character. `r` un-reverses the stack. Then, the program sees the C-link and moves to the next link `p`, and prints the stack.

Case 2: the program moves to the last link `p`, which merely prints the entire stack.
> 2 votes

# Answer
## PowerShell, 40 bytes

```
param($x,$y)(("ACE","ACD")[$y],"AB")[$x]

```

Nested arrays indexed by input. In PowerShell, `$true` / `1` and `$false` / `0` are practically equivalent (thanks to very loose typecasting), so that indexes nicely into a two-element array. This is really as close to a ternary as PowerShell gets, and I've used it plenty of times in golfing.

### Examples

```
PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 1
AB

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 1 0
AB

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 1
ACD

PS C:\Tools\Scripts\golfing> .\do-while-false.ps1 0 0
ACE

```
> 2 votes

# Answer
# K, 37 bytes

```
{?"ABCDE"@0,x,(1*x),(2*~x),(~x)*3+~y}

```
> 2 votes

# Answer
# Vitsy, 26 bytes

Expects inputs as 1s or 0s through STDIN with a newline separating.

```
W([1m;]'DCA'W(Zr1+rZ
'BA'Z
```

~~I actually discovered a serious problem with if statements during this challenge. D: This is posted with the broken version, but it works just fine. (I'll update this after I fix the problem)~~ Please note that I have updated Vitsy with a fix of if/ifnot. This change does not grant me any advantage, only clarification.

Explanation:

```
W([1m;]'DCA'W(Zr1+rZ
W                      Get one line from STDIN (evaluate it, if possible)
 ([1m;]                If not zero, go to the first index of lines of code (next line)
                       and then end execution.
       'DCA'           Push character literals "ACD" to the stack.
            W          Get another (the second) line from STDIN.
             (         If not zero,
do the next instruction.
              Z        Output all of the stack.
               r1+r    Reverse the stack, add one (will error out on input 0, 1), reverse.
                   Z   Output everything in the stack.

'BA'Z
'BA'                   Push character literals "AB" to the stack.
    Z                  Output everything in the stack.
```

Try it Online!
> 2 votes

# Answer
# Jelly, 14 bytes

```
Ḥoị“ACD“AB“ACE

```

This expects the Booleans (**1** or **0**) as separate command-line arguments. Try it online!

### How it works

```
Ḥoị“ACD“AB“ACE  Main link. Left input: C1. Right input: C2.

Ḥ               Double C1. Yields 2 or 0.
 o              Logical OR with C2.
                2o1 and 2o0 yield 2. 0o1 and 0o0 yield 1 and 0, resp.
   “ACD“AB“ACE  Yield ['ACD', 'AB', 'ACE'].
  ị             Retrieve the string at the corresponding index.

```
> 2 votes

# Answer
# beeswax, 26 bytes

Interpreting `0` as false, `1` as true.

```
E`<
D`d"`C`~<
_T~T~`A`"b`B

```

Output:

```
julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i1
i1
AB
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i1
i0
AB
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i0
i1
ACD
Program finished!

julia> beeswax("codegolfdowhile.bswx",0,0.0,Int(20000))
i0
i0
ACE
Program finished!

```

Clone my beeswax interpreter from my Github repository.
> 2 votes

# Answer
# C, ~~47~~ 45 bytes

Since there are only 3 different outcomes, we can pick one of three strings like this:

```
char*f(c,d){return"AB\0 ACE\0ACD"+(!c<<d+2);}

```

Thanks to Herman L for 2 bytes

## Demo

```
#include<stdio.h>
int main()
{
    printf("%s\n%s\n%s\n%s\n",
           f(1,1),
           f(1,0),
           f(0,1),
           f(0,0));
}

```
> 2 votes

# Answer
## Perl, 23 bytes

```
say<>>0?AB:<>>0?ACD:ACE

```

Requires the `-E`|`-M5.010` flag and takes input as 1 and 0:

```
$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n0'
ACE
$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'0\n1'
ACD
$ perl -E'say<>>0?AB:<>>0?ACD:ACE' <<< $'1\n0'
AB

```

Alternative solution that requires `-p` and is 22 + 1 = 23 bytes:

```
$_=/^1/?AB:/1/?ACD:ACE

```

```
perl -pe'$_=/^1/?AB:/1/?ACD:ACE' <<< '0 1'

```
> 1 votes

# Answer
# 05AB1E, ~~23~~ 20 bytes

Code:

```
Ii"AB"?q}"AC"?69I-ç?

```

Try it online!
> 1 votes

# Answer
# Japt, 19 bytes

```
"A{U?'B:'C+(V?'D:'E

```

Test it online!

Fun fact: This would be 16 bytes if it weren't for a bug:

```
"A{U?"B:C{V?"D:E

```
> 1 votes

# Answer
# SMBF, 39 bytes

Each `_` represents a null literal `\x00` and is used for readability. I've successfully tested it for all test cases. ~~except the third, because I haven't found a way to test that input on my interpreter, since I'd need stdin to be `\x00\x01`. I know it works, though, because I used the exact same method for testing C2 as I did for testing C1.~~

```
<.<,[<]<<.[>]>[<<<]<<<<,[<]<<.DE__BC__A

```

### Explanation:

```
<.          print A
<,          read C1
[<]         if true, move left one
<<.         move left 2 and print (C if false, B if true)
[>]>        move to C1
[<<<]       if true, our output is done, so move all the way left, so further code is NOP
<<<<,       move left 4 and read C2
[<]         if true, move left one
<<.         move left 2 and print (E if false, D if true)
DE_ BC_ A   data on the tape

```

I think this will do the same for the same byte count, reusing B and C by adding 2 to each:

```
<.<,[<]<<.[>]>[<<]<<++<++>>,[<]<<.BC__A

```
> 1 votes

# Answer
# Kotlin, 50 bytes

It is interesting what one can do with string templates.

```
{a,b->"A${if(a)"B" else "C${if(b)"D" else "E"}"}"}

```

Try Here
> 1 votes

# Answer
# Mouse-2002, 23 bytes

```
??"A"["B"|"C"["D"|"E"]]

```

Switches on two inputs, which each should be either `0` for `false` or anything else for `true`.

Ungolfed, as a function:

```
#Y,?,?;

$Y 1% a: 2% b:
  "A"
  a [
    "B"
  |
    "C"
    b [
      "D"
    |
      "E"
    ]
  ]
$

```

Brackets just test if the top of the stack is true, and `|` is `else`.

This is a translation of @Cᴏɴᴏʀ O'Bʀɪᴇɴ's ES6 answer.
> 1 votes

# Answer
# PHP 4.1, 19 bytes

I was expecting it to be harder, but well. It was really fun!

```
<?=A,$A?B:C.($B^t);

```

This expects 2 parameters/values, passed as strings over POST/GET/SESSION/COOKIE... The key `A` will have the first value, the key `B` will have the 2nd.
The result will be sent to STDOUT.
> 1 votes

# Answer
# DUP, 29 bytes

```
['A,^['B,]['C,$['D,]['E,]?]?]

```

`Try it here!`

Anonymous lambda. Usage:

```
1 0['A,^['B,]['C,$['D,]['E,]?]?]!

```

# Explanation

```
[                           ] {lambda}
 'A,                          {output A}
    ^                         {check if arg1 is truthy}
     [   ][               ]?  {conditional}
      'B,                     {if so, output B}
           'C,                {otherwise, output C...}
              $               {...and check if arg2 is truthy}
               [   ][   ]?    {conditional}
                'D,           {if so, output D}
                     'E,      {otherwise, output E}

```
> 1 votes

# Answer
# , 18 chars / 23 bytes

```
`A⏜î?⍘B:`C⏜í?⍘D:⍘E

```

`Try it here (Firefox only).`

It's pretty much a fusion of conditional statements.

Note:  basically takes all code up to an optional , interprets the code, and replaces that block in the code with the result. This is the first time I've used this in a submission, but it works quite well. Self-modifying code FTW!
> 1 votes

# Answer
# \>\<\> (Fish), 30 bytes

```
"A"o$1+.
"<"DC"v"CE
o "B"|>oo;

```

This code uses the two variables (using the initial stack) to move the pointer to (C2, C1+1) You can try it here
> 1 votes

# Answer
## Perl, 19 + 1 (-p switch) = 20 bytes

```
$ perl -pe '$_=l.$_^-su;s/B./B/'
00
ACE
01
ACD
10
AB
11
AB

```

Uses string XOR and a bareword with leading hyphen. Ungolfed:

```
$_ = ('l' . $_) ^ '-su';
s/B./B/;

```
> 1 votes

# Answer
## QBIC, ~~39~~ 34 bytes

EDIT: Found out that QBasic (and by extension QBIC) doesn't need an `=1` to test if an input `is true`, so removed those.

```
_!_!~a_>?@AB._X]~b_>?@ACD._E?@ACE.

```

---

Original answer:

```
_!_!~a=1_>?@AB._X]~b=1_>?@ACD._X]?@ACE.

```

Takes two numerical inputs and tests these in straight-forward IF's. No fancy OR logic and array indexes here, unfortunately.
> 1 votes

# Answer
## C, 42 bytes (long version); 31 (short version)

The existing submissions seem inconsistent with regards to whether the variables must be named C1 and C2, and whether actually printing the results is required, so I've done a long and short version.

This approach takes advantage of the fact that most of the possibilities for each index differ by only one bit.

Long version:

```
char s[4]={65,67-C1,69*!C1&69-C2};puts(s);

```

Short version:

```
char s[4]={65,67-a,69*!a&69-b};

```
> 1 votes

# Answer
# ForceLang,124 bytes

```
def f io.readnum()
set w io.write
set g goto
w "A"
if f
g L
w "C"
if f
g M
w "E"
g N
label L
w "B"
g N
label M
w "D"
label N

```
> 1 votes

# Answer
# Go, 120 bytes

```
func w(b bool,d bool)(r string){
for i:=true;i;i=!i{
r+="A"
if b{r+="B"
break}
r+="C"
if d{r+="D"
break}
r+="E"}
return}

```

Go has only one loop structure, `for`, but you can simulate a do-while loop with `for i := true; i; i = expr`.

Edit: It also happens that Go's `switch` statement is flexible enough to replicate this.

```
switch {
case true:
    r += "A"
    if b {
        r += "B"
        break
    }
    r += "C"
    if d {
        r += "D"
        break
    }
    r += "E"
}

```
> 1 votes

# Answer
# D, 35 bytes

```
(int a,int b)=>a?"AB":"AC"+"ED"[b];

```

Hey, look, D has lambdas.

Hey, look, D is JavaScript, but longer. :^(

Copied *verbatim* from Conor's ES6 answer. c:
> 1 votes

# Answer
# FALSE, 16 bytes

```
$"A"'C+,~['E+,]?

```

Input values are on the stack (first C2 then C1), false is 0 and true is -1 (this is normal in FALSE)
> 1 votes

# Answer
# Hexagony, ~~28~~ ~~26~~ 25 bytes

```
A;?.));?~..>);@</E"+;@}/>

```

*-2 bytes by moving up the printing of **AB***

*-1 byte by incrementing to C instead*

**Try it online!**

Expanded:

```
   A ; ? .
  ) ) ; ? ~
 . . > . ; @
< / E " + ; @
 } / > . . .
  . . . . .
   . . . .

```

---

Uses the value of the second input to get the last char, removing the need for another costly branch:
```
"E" + (-1*C2)

```

*Credit to @JoKing*
Alternatively I could have also just subtracted the value which doesn't save any bytes though:

```
"E" - C2

```
> 1 votes

# Answer
## CJam, 25 bytes

```
'Aq~[{'C\['E'D]=}{;'B}]=~

```

Try it online

Not the best way to do it, but it works.
> 0 votes

# Answer
# Jolf, 16 bytes

```
+'A?j'B+'C."DE"J

```

Simple. Try this one here!

Aother one, using that other Pyth answer's approach:

11 characters, 18 UTF-8 bytes. You can try this one here.

```
~T."૎્««"Ιj
          ^-- that's a capital Iota, converting input to binary

```
> 0 votes

# Answer
# Brainbash, 43 bytes

```
----[>+<----]>++.>#{<+.>}-{<++.+>#-{<+>}<.}

```

Brainbash is BF with two tapes and more stuff. We're only using one this time. Let's take a look:

```
----[>+<----]>++.

```

This sets the first cell to `A` and outputs it.

```
>#

```

This move to the next cell and takes numeric input

```
{<+.>}

```

This is an if statement. If the numeric input is one, then we'll increment the previous cell and output it, outting `B`.

```
-

```

This transforms `1` to `0` (falsey) and `0` to `255`. It's effectively a boolean NOT as far as the next if statement is concerned.

```
{<++.

```

If the current bit, output a `C`.

```
+>#

```

Change it do a `D` and take some input

```
-

```

"Negate it"

```
{<+>}

```

If it was a zero, output an increment and return to input cell.

```
<.}

```

Move to destination cell and out it.

---

I could use the "heat death of the universe" to save two bytes, using `>+[+[<]>>+<+]>`, but that didn't complete in the online interpreter, which can be found in the link in the header.
> 0 votes

# Answer
# MATLAB, ~~31~~ 28 bytes

```
@(x,y)[65,67-x,~x*(69-y),'']

```

This anonymous function will match all the test cases. The first input is `condition 1` and the second input is `condition 2`. The string will be returned.

The function also works with **Octave**. You can try it online here.

Simply create the anonymous function by running the command above, then call the function. Running this for example:

```
ans(0,1)

```

Will return:

```
ACD

```
> 0 votes

# Answer
# C, 54 bytes

Since the story started with a loop, I decided to stick to that. Not the shortest of solutions; but certainly one of the more obscure ones.

Function `f` takes two integer parameters as input (1 = true, 0 = false), and outputs `AB`, `ACD` or `ACE` to stdout.

```
f(a,b){for(int x=64;~putchar(++x)<<a&4;x+=x&2?!b:!a);}

```
> 0 votes

# Answer
# Nustack, 27 bytes

```
a"AB"*"AC"b{"E"}{"D"}if + |

```

Thanks to Morgan Thrapp and her Python answer for giving me the inspiration for this one.

Explanation:

```
a"AB"* /* Repeat "AB" 0 or 1 times, depending on if a is #t or #f. The result ("" or "AB") is put on the stack */
"AC" /* Put "AC" on the stack */
b{"E"}{"D"}if /* If b is true, push "E", else push "D" */
+ /* Concatenate the top two strings on the stack, push the result ("ACE" or "ACD") */
| /* Right now the stack looks like (x y). If x is truthy (not empty), keep x, else keep y */

```
> 0 votes

# Answer
## Javascript, 43 Bytes

A different (more intuitive?) way to do it in JS. The name `parseInt` is not inductive of Code Golfing :P

```
"A"+["CE","CD","B","B"][parseInt(x+""+y,2)]

```

## Test:

```
var cases = ["00","01","10","11"];

for (i=0;i<4;i++) {
   var x = cases[i][0];
   var y = cases[i][1];
   document.write("A"+["CE","CD","B","B"][parseInt(x+""+y,2)]+"<br>")
}
```
> 0 votes

# Answer
# Ruby, 31 bytes

Anonymous function; assign to a variable to test its output.

```
->x,y{?A+(x ??B:?C+(y ??D:?E))}

```
> 0 votes

# Answer
# SmileBASIC, 32 bytes

```
INPUT A,B?"A"+"CB"[A]+"ED"[B]*!A

```
> 0 votes

# Answer
# C++, ~~57~~ 52 bytes

```
[](auto c,auto&s){s="AC";c[0]?--s[1],s:s+='E'-c[1];}

```

First argument should be an indexable collection (vector, array, etc) of conditions, and second argument is the string to write to.

Assumes that the runtime character set has `B` and `C` contiguous, and `D` and `E` also contiguous (both are true for common codings such as ASCII and EBCDIC).

## Demo

```
auto const f = [](auto c,auto&s){s="AC";c[0]?--s[1],s:s+='E'-c[1];};

#include<array>
#include<iostream>
#include<string>
int main()
{
    std::string s;

    for (bool c1: {true, false})
        for (bool c2: {true, false})
            f(std::array{c1, c2}, s),std::cout << s << '\n';
}

```
> 0 votes

# Answer
# Forth (gforth), 54 bytes

I had orignally planned on using emit for this, but realized that direct string output was shorter (61 vs 54 bytes)

```
: f if ." AB" else if ." ACD" else ." ACE" then then ;

```

Try it online!

### Explanation

If C1 is true, it prints `AB`, otherwise it prints `ACD` if C2 is true, and `ACE` if C2 is false

### Code Explanation

```
: f                \ start a new word definition
   if              \ if c1 is true
      ." AB"       \ print "AB"
   else            \ if c1 is false
      if           \ if c2 is true
         ." ACD"   \ print "ACD"
      else         \ if c2 is false
         ." ACE"   \ print "ACE"
      then         \ end the inner if
   then            \ end the outer if
;                  \ end the word defintion

```
> 0 votes

---
Tags: code-golf
---


title: Fill up to duplicate ranges

text:
# Question
Title: Fill up to duplicate ranges
Let \\$L\\$ be a list of positive integers with no particular ordering, and which can contain duplicates. Write a program or function which outputs a list of positive integers \\$M\\$ (whose ordering is unimportant) such that merging \\$L\\$ and \\$M\\$ results into the smallest list which can entirely split into identical ranges of integers \\$\[1..i\]\\$, where \\$i\\$ is the biggest element in \\$L\\$

### Example

Let `L = [5,3,3,2,7]`. The maximum element of `L` is `7`. The most times a specific integer occurs is `2` (`3` appears 2 times). Therefore, we need to output the list `M` that will allow to complete `L` so that we can construct `2` ranges of integers from `1` to `7`.

Therefore, we need to output `M = [1,1,2,4,4,5,6,6,7]`, so that each integer from `1` to `7` appears `2` times.

### Inputs and outputs

* Use anything in your language that is similar to lists. The data structure used for the input and the output must be the same.
* The input list will contain only positive integers.
* The input list will not be empty.
* You **cannot** assume the input list is sorted.
* The ordering in the output list is unimportant.

### Test cases

```
Input                  Output
[1]                    []
[7]                    [1, 2, 3, 4, 5, 6]
[1, 1, 1]              []
[1, 8]                 [2, 3, 4, 5, 6, 7]
[3, 3, 3, 3]           [1, 1, 1, 1, 2, 2, 2, 2]
[5, 2, 4, 5, 2]        [1, 1, 3, 3, 4]
[5, 2, 4, 5, 5]        [1, 1, 1, 2, 2, 3, 3, 3, 4, 4]
[5, 3, 3, 2, 7]        [1, 1, 2, 4, 4, 5, 6, 6, 7]

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
> 6 votes
# Jelly, 9 bytes

Saved 1 byte thanks to Jonathan Allan. The footer calls the main link, sorts the result to match the test cases and formats the output as a grid.

```
RṀẋLƙ`Ṁœ-

```

Try it online! or Check out a test suite!

### Alternatives

```
ṀRẋLƙ`Ṁœ-
RṀẋṢŒɠṀƊœ-
ṀRẋṢŒɠṀƊœ-
LƙɓṀRẋṀœ-⁸
LƙɓRṀẋṀœ-⁸

```

Try one of them online!

### Explanation

```
ṀRẋLƙ`Ṁœ-   Full program. N = Input.
ṀR          Range from 1 to max(N): [1 ... max(N)]
   Lƙ`      Map length over groups formed by identical elements.
  ẋ         Repeat the range T times, for each T in the result of the above.
      Ṁ     Maximum. Basically, get the range repeat max(^^) times.
       œ-   Multiset difference with N.

```

# Answer
> 7 votes
# Perl 6, ~~37~~ 33 bytes

*-4 bytes thanks to nwellnhof!*

```
{^.keys.max+1 xx.values.max∖$_}

```

Try it online!

Anonymous code block that takes a Bag and returns a Bag of values.

### Explanation:

```
{                             } # Anonymous code block
 ^.keys.max+1  # Create a range from 1 to the maximum value of the list
              xx  # Multiply the list by:
                .values.max      # The amount of the most common element
                           ∖$_   # Subtract the original Bag

```

# Answer
> 6 votes
# , ~~59~~ ~~49~~ 48 bytes

```
rep(s<-1:max(L<-scan()),max(y<-table(c(L,s)))-y)

```

Try it online!

# Answer
> 5 votes
# Python 2, ~~86~~ ~~83~~ ~~80~~ 72 bytes

```
def f(l):m=range(1,max(l)+1)*max(map(l.count,l));map(m.remove,l);print m

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~17~~ ~~16~~ ~~17~~ 11 bytes

```
ZLŠ¢àиIð.;þ

```

-1 byte thanks to *@Mr.Xcoder*.
+1 byte after bug-fixing the work-around..
-5 bytes by using the new 05AB1E version and -1 byte because ordering of the output is unimportant

Maybe I completely look past it, but does 05AB1E even have a remove all elements of list **b** from list **a**.. (EDIT: It indeed doesn't..) I know how to remove all multiple times, but not once each.. (multiset difference)

Try it online or verify all test cases.

**Explanation:**

```
Z      # Push the maximum of the (implicit) input-list (without popping)
       #  i.e. [5,3,3,2,7] → 7
 L     # Pop and push a list in the range [1,max]
       #  → [1,2,3,4,5,6,7]
  Š    # Tripleswap: a,b,c → c,a,b, so input,[1,max] to [1,max],input,input
   ¢   # Count for each value in the input-list how many times it occurs
       #  → [1,2,2,1,1]
    à  # Pop and push the maximum count
       #  → 2
     и # Repeat the list [1,max] that many times
       #  → [1,2,3,4,5,6,7,1,2,3,4,5,6,7]

       #Now the work-around bit because 05AB1E lacks a builtin for multiset difference..
Ið.;   # Replace first occurrence of the values in the input-list with a space " "
       #  → [1," "," ",4," ",6," ",1,2," ",4,5,6,7]
    þ  # Remove all spaces by only keeping digits
       #  → [1,4,6,1,2,4,5,6,7]
       # (after which the result is output implicitly)

```

# Answer
> 3 votes
# , ~~59~~ 55 bytes

Using the `vecsets` package we can drop the answer length some. With `gl` we can get the ordered output. This doesn't work in TIO. Following @digEmAll's style of (rather clever) solution without a function definition, this can be considered a 55 byte solution.

```
vecsets::vsetdiff(c(gl(m<-max(L<-scan()),sum(L==m))),L)

f=function(x){scan<-function()x
vecsets::vsetdiff(c(gl(m<-max(L<-scan()),sum(L==m))),L)
}

f(c(1))                # expected: integer(0)
f(c(7))                # expected: c(1, 2, 3, 4, 5, 6)
f(c(1, 1, 1))          # expected: integer(0)
f(c(1, 8))             # expected: c(2, 3, 4, 5, 6, 7)
f(c(3, 3, 3, 3))       # expected: c(1, 1, 1, 1, 2, 2, 2, 2)
f(c(5, 2, 4, 5, 2))    # expected: c(1, 1, 3, 3, 4)
f(c(5, 2, 4, 5, 5))    # expected: c(1, 1, 1, 2, 2, 3, 3, 3, 4, 4)

```

# Answer
> 3 votes
# JavaScript (ES6), 98 bytes

This turned out to be pretty hard to golf below 100 bytes. There may be a better approach.

```
a=>(a.map(o=M=m=n=>m=(c=o[M=n<M?M:n,n]=-~o[n])<m?m:c),g=k=>k?o[k]^m?[...g(k,o(k)),k]:g(k-1):[])(M)

```

Try it online!

### How?

We first walk through the input array `a[]` to gather the following data:

* `M` = highest element found in the input array
* `m` = highest number of occurrences of the same element
* `o[n]` = number of occurrences of `n`

Note that `o` is primarily defined as a function, but the underlying object is also used to store the number of occurrences.

```
a.map(                      // a[] = input array()
  o =                       // o = callback function of map()
  M = m =                   // initialize m and M to non-numeric values
  n =>                      // for each value n in a[]:
    m = (                   //   this code block will eventually update m
      c = o[                //     c = updated value of o[n]
        M = n < M ? M : n,  //     update M to max(M, n)
        n                   //     actual index into o[]
      ] = -~o[n]            //     increment o[n]
    ) < m ?                 //   if o[n] is less than m:
      m                     //     let m unchanged
    :                       //   else:
      c                     //     set it to c
)                           // end of map()

```

We then use the recursive function `g()` to build the output.

```
(g = k =>                   // k = current value
  k ?                       // if k is not equal to 0:
    o[k] ^ m ?              //   if o[k] is not equal to m:
      [ ...g(k, o(k)),      //     increment o[k] and do a recursive call with k unchanged
        k ]                 //     append k to the output
    :                       //   else:
      g(k - 1)              //     do a recursive call with k - 1
  :                         // else:
    []                      //   stop recursion
)(M)                        // initial call to g() with k = M

```

# Answer
> 3 votes
# Brachylog, ~~18~~ 17 bytes

```
⌉⟦₁;Ij₎R⊇p?;.cpR∧

```

Try it online!

*Saved 1 byte thanks to @Kroppeb.*

### Explanation

```
⌉                  Take the largest element in the Input
 ⟦₁                 Construct the range [1, …, largest element in the Input]
   ;Ij₎R            Juxtapose that range to itself I times, I being unknown;
                       call the result R
       R⊇p?         The Input must be an ordered subset of R, up to a permutation
          ?;.c      Concatenate the Input and the Output
                       (the Output being unknown at this point)
              pR    This concatenation must result in R, up to a permutation
                ∧   (Find a fitting value for the Output that verifies all of this)

```

# Answer
> 3 votes
## Haskell, 72 bytes

```
import Data.List
f l=(last(sortOn(0<$)$group$sort l)>>[1..maximum l])\\l

```

Try it online!

```
            sort l      -- sort input list
       group            -- group identical elements
   sortOn(0<$)          -- sort by length
 last                   -- take the last element, i.e. the list
                        -- of the most common element
      >>[1..maximum l]  -- replace each of it's elements
                        -- with the list [1..maximum l]
  \\l                   -- remove elements of the input list

```

# Answer
> 2 votes
# Java 10, 186 bytes

```
import java.util.*;L->{Integer m=0,f=0,t;for(int i:L){m=i>m?i:m;f=(t=Collections.frequency(L,i))>f?t:f;}var r=new Stack();for(;m>0;m--)for(t=f;t-->0;)if(!L.remove(m))r.add(m);return r;}

```

Try it online.

**Explanation:**

```
import java.util.*;   // Required import for Collections and Stack
L->{                  // Method with Integer-list as both parameter and return-type
  Integer m=0,        //  Max, starting at 0
          f=0,        //  Max frequency, starting at 0
          t;          //  Temp integer
  for(int i:L){       //  Loop over the input-List
    m=i>m?i:m;        //   If the current item is larger than the max, set it as new max
    f=(t=Collections.frequency(L,i))>f?t:f;}
                      //   If the current frequency is larger than the max freq, set it as new max
  var r=new Stack();  //  Result-List
  for(;m>0;m--)       //  Loop the maximum in the range [m,0)
    for(t=f;t-->0;)   //   Inner loop the frequency amount of times
      if(!L.remove(m))//    Remove `m` from the input list
                      //    If we were unable to remove it:
        r.add(m);     //     Add it to the result-List
  return r;}          //  Return the result-List

```

# Answer
> 2 votes
# Husk, 12 bytes

Saved 1 byte thanks to BWO.

```
S-§*oḣ▲(▲Ṡm#

```

Try it online!

# Answer
> 2 votes
# MATL, ~~24~~ 21 bytes

```
X>:GS&Y'X>yGhS&Y'q-Y"

```

Try it online!

# Answer
> 2 votes
# MATL, 14 bytes

Input is a column vector, with `;` as separator.

```
llXQtn:yX>b-Y"

```

Try it online! Or verify all test cases (this displays `--` after each output so that empty output can be identified).

### Explanation

Consider input `[5; 2; 4; 5; 5]` as an example.

```
llXQ     % Implicit input. Accumarray with sum. This counts occurrences
         % of each number, filling with zeros for numbers not present
         % STACK: [0; 1; 0; 1; 3]
tn:      % Duplicate, number of elements, range
         % STACK: [0; 1; 0; 1; 3], [1 2 3 4 5]
yX>      % Duplicate from below, maximum of array
         % STACK: [0; 1; 0; 1; 3], [1 2 3 4 5], 3
b        % Bubble up
         % STACK: [1 2 3 4 5], 3, [0; 1; 0; 1; 3]
-        % Subtract, element-wise
         % STACK: [1 2 3 4 5], [3; 2; 3; 2; 0]
Y"       % Repelem (run-length decode). Implicit display
         % STACK: [1 1 1 2 2 3 3 3 4 4]

```

# Answer
> 1 votes
# Pyth, 13 bytes

```
.-*SeSQeSlM.g

```

Try it here! or Check out a test suite!

# Answer
> 1 votes
# Charcoal, 19 bytes

```
Ｆ…·¹⌈θＥ⁻⌈Ｅθ№θκ№θιＩι

```

Try it online! Link is to verbose version of code. Would have been 16 bytes if the integers had been non-negative instead of positive. Explanation:

```
     θ              First input
    ⌈               Maximum
 …·¹                Inclusive range starting at 1
Ｆ                   Loop over range
          θ         First input
         Ｅ          Loop over values
            θ       First input
             κ      Inner loop value
           №        Count occurrences
        ⌈           Maximum
               θ    First input
                ι   Outer loop value
              №     Count occurrences
       ⁻            Subtract
      Ｅ             Map over implicit range
                  ι Current value
                 Ｉ  Cast to string
                    Implicitly print on separate lines

```

# Answer
> 1 votes
# APL (Dyalog Classic), ~~18~~ 17 bytes

```
∊{⊂⍳⌈/⍵}~¨∘↓∘⍉⊣¨⌸

```

Try it online!

uses `⎕io←1`

# Answer
> 1 votes
# Prolog (SWI), 211 bytes

It's been a while since I programmed in Prolog. Can definitely be golfed further, but I have an exam to study for hahaha.

### Code

```
f(L,X):-max_list(L,M),f(L,M,[],X,M).
f([],0,_,[],_).
f(L,0,_,A,M):-f(L,M,[],A,M).
f([],I,H,[I|A],M):-N is I-1,f(H,N,[],A,M).
f([I|R],I,H,A,M):-append(H,R,S),f(S,I,[],[I|A],M).
f([H|R],I,G,A,M):-f(R,I,[H|G],A,M).

```

Try it online!

### Ungolfed version

```
f(List, Result) :-
    max_list(List, MaxIndex),
    f(List, MaxIndex, [], Result, MaxIndex).

f([], 0, _, [], _).

f(List, 0, _, Acc, MaxIndex) :-
    f(List, MaxIndex, [], Acc, MaxIndex).

f([], Index, History, [Index | Acc], MaxIndex) :-
    NewIndex is Index - 1, f(History, NewIndex, [], Acc, MaxIndex).

f([Index | Remaining], Index, History, Acc, MaxIndex) :-
    append(History, Remaining, Result),
    f(Result, Index, [], [Index | Acc], MaxIndex).

f([Head | Remaining], Index, History, Acc, MaxIndex) :-
    f(Remaining, Index, [Head | History], Acc, MaxIndex).

```

# Answer
> 1 votes
## Clojure, 94 bytes

```
#(for[F[(frequencies %)]i(range 1(+(apply max %)1))_(range(-(apply max(vals F))(or(F i)0)))]i)

```

# Answer
> 1 votes
# C++, 234 bytes

```
#include<vector>
#include<map>
using X=std::vector<int>;
X f(X x){int q,z;q=z=0;std::map<int,int>y;X o;
for(auto i:x)++y[i];for(auto i:y)q=q>i.second?q:i.second;
for(;++z<=y.rbegin()->first;)for(;y[z]++<q;)o.push_back(z);return o;}

```

(Newlines in the function body are for readability).

The function takes and returns a vector of ints. It utilizes `std::map` for finding the max element of the input list and also for counting the occurrences of each distinct element.

Explanation:

```
// necessary includes. Note that each of these is longer than whole Jelly program!
#include <vector>
#include <map>

// this type occurs three times in the code
using X = std::vector<int>;

// The function
X f (X x)
{
   // initialize some variables
   int q, z; // q will hold the max count
   q = z = 0;
   std::map <int, int> y; // The map for sorting
   X o; // The output vector

   // Populate the map, effectively finding the max element and counts for all of them
   for (auto i : x)
       ++y[i];

   // find the max count
   for (auto i : y)
       q = q > i.second ? q : i.second;

   // Populate the output vector

   // Iterate all possible values from 1 to the max element (which is the key at y.rbegin ())
   // Note that z was initialized at 0, so we preincrement it when checking the condition
   for (; ++z <= y.rbegin ()->first;)
       // for each possible value, append the necessary quantity of it to the output
       for(; y[z]++ < q;)
           o.push_back (z);

   return o;
}

```

# Answer
> 1 votes
# Gaia, 12 bytes

```
::⌉┅¤:C¦⌉&¤D

```

Try it online!

# Answer
> 1 votes
# C (gcc), 177 bytes

Input and output are done through stdin and stdout. Both arrays are capped at 2^15 elements, but they could be as large as 2^99 elements.

```
f(j){int n=0,m=0,i=0,a[1<<15],b[1<<15]={0};for(;scanf("%i",&a[i])>0;i++)j=a[i],m=j>m?j:m,b[j-1]++;for(i=m;i--;)n=b[i]>n?b[i]:n;for(i=m;i--;)for(j=n-b[i];j--;)printf("%i ",i+1);}

```

With some formatting:

```
f(j){
  int n=0, m=0, i=0, a[1<<15], b[1<<15]={0};
  for(;scanf("%i",&a[i])>0;i++) j=a[i], m=j>m?j:m, b[j-1]++;
  for(i=m;i--;) n=b[i]>n?b[i]:n;
  for(i=m;i--;) for(j=n-b[i];j--;) printf("%i ",i+1);
}

```

Try it online!

---
Tags: code-golf, array, integer
---


title: The Time Traveler

text:
# Question
Title: The Time Traveler
*The shortest code to generate the correct times on the clocks wins.*

You are a seasoned time traveler and have been known to stop at many planets during your journies. Each planet rotates at a different rate and because of this, the length of a day is different than our usual 24-hour day. As a result, the planets use clocks with different numbers of hours. The hours on a clock with *x* hours are arranged similar to ours (1, 2, 3, ... , *x*) with the number rotating clockwise and *x* being at the top.

Additionally, each planet has a different amount of minutes in an hour, and a different number of seconds in a minute. You will be given a starting time and a number of elapsed seconds from which you must determine the ending time.

Input can be taken directly from a file passed as an argument, or as standard input. The first line of input will be the number of clocks you need to process. After that, each clock has three lines of input that contains integers in the following format:

```
x y z
h m s
t

```

The meaning of each letter is below.

> x = The number of hours in a day (2 \<= x \<= 99)
> y = The number of minutes in an hour (2 \<= y \<= 100)
> z = The number of seconds in a minute (2 \<= z \<= 100)
> h = The hour of the starting time (1 \<= h \<= x)
> m = The minute of the starting time (0 \<= m \< y)
> s = The second of the starting time (0 \<= s \< z)
> t = The number of seconds that have elapsed

The output must be the ending time for each clock after *t* seconds have passed since the starting time. Your output must be formatted as standard clock time (HH:MM:SS). Numbers should be padded, when necessary, to ensure that all numbers are two-digits.

## Test Cases

---

**Input**

```
2
5 20 10
1 10 5
2633
6 25 5
6 0 3
290

```

**Output**

```
04:13:08
02:08:03

```

---

**Input**

```
1
14 17 11
12 16 10
1530

```

**Output**

```
07:03:00

```

---

**Input**

```
2
8 40 25
3 1 15
10620
14 15 20
1 14 0
-580

```

**Output**

```
05:26:10
14:00:00

```

# Answer
> 8 votes
## GolfScript - 50 chars

```
~](;7/{{~+.4$/\4$%])\}3*3<)@\or\+{100+`(;}%':'*n}%

```

The values (H/M/S) are collected by moving them to the front of the stack (`])\`). The hour 'underflow' at 0 is handled with `or`. Zero padding is handled with `100+`(;`, although I suppose `0`\+-2>` is the same length.

# Answer
> 9 votes
## Python, 142 characters

```
R=raw_input
for i in' '*input():x,y,z,h,m,s=map(int,(R()+i+R()).split());t=input()+h*y*z+m*z+s;print'%02d:%02d:%02d'%((t/y/z-1)%x+1,t/z%y,t%z)

```

# Answer
> 5 votes
# GolfScript 62 60 characters

Edit: I managed to get the array formerly stored in a to reside on the stack, it takes a little extra switching that way though so no major improvement.

```
~](\7/\{(~+[]\{.5$/@@5$%\+@@+}3*;\;(@or\+{'0'\+-2>}%':'*n@}*

```

62 version:

```
~](\7/\{[]:a;(~{+.4$/\4$%a+:a;}3*;;;a(@or\+{'0'\+-2>}%':'*n@}*
1______a2____3_b4_5___6__7____8__9__10_____11_________12____13

```

I'm sure it can be done a lot better, I just couldn't think of anything better.

1: Make an array of all input, pick off the first element, group the rest into blocks of 7.
a/13: Consume the first number from the input to run the loop that number of times.
2: Store an empty array in a.
3: Pick a block of 7 and expand it to 7 individual numbers.
b/8: Run a loop 3 times, once for each of seconds, minutes and hours.
4: Add the last two numbers together, for the first iteration that is seconds and time to shift, for the following it is minutes and hour with the overflow from the previous cycle. Make a second copy of the result.
5: Divide the copy by it's limit to produce the overflow and shift the result back one space.
6: Calculate the modulo of the previous division to produce a part of the result.
7: Add this part to the a array.
9: Remove the hour overflow and the second and minute limits from the stack.
10: Take the hour part of a, if it's zero replace it with the hour limit, put it back in the array.
11: For each element in a, place '0' in front, thus converting to string, and throw away everything but the last 2 characters.
12: Collapse the array into a single string delimited by ':', place a newline and shift the array containing the remaining jobs to the front of the stack, thus preparing for the next iteration.

# Answer
> 5 votes
## J (172/35) 137 99 107

**Now passes all given test cases.**

```
4(1!:2)~LF,~"1([,':',])/"2,"2":"0(10 10#:1 0 0+{.#:{.&{:+{.#.1 0 0-~1&{)"2&(,&}.$~,&3 3&{.&{.)".;._2(1!:1)3

```

172 is the whole thing; 35 is the number of characters I would give if I was really snooty and refused to do the IO as indicated. (I still modified it a little bit; clocks is a function taking a filename meant to be used interactively within J.)

I sure hope this is a lot easier in J than I make it look.

Edit: Figured out how to do better input parsing in J, eliminated charsub, switched to command line invocation & output.

Edit 2: Changed input of central function to 3x3 matrix, eliminated many pesky parentheses, eliminated names

Edit 3: 0-o'clock handled.

Explanation:

My J still isn't great, and IO is a pain as always. So bits of this are loony.

* The verb `1 0 0+{.#:{.&{:+{.#.1 0 0-~1&{` takes a three by three matrix (consisting of the input lines, the last two elements are garbage)
* The h/m/s is gotten with {. (head), the actual time with 1&{ (second element), and the second count with {.&{: (head of tail).
* The verb uses #. to transform the clock time to seconds. (See documenation.)
* It adds the second count and then uses #: to get the 3 element answer.
* The 0 o'clock case is handled by subtracting 1 from the hour before the base change and adding 1 back after. (the two bits with `1 0 0`)
* The rest is input and output, which is really grubby (as always).
* `".;._2(1!:1)3` gets a 3 'column' matrix of the input with 0s in unfilled positions.
* `,&}.$~,&3 3&{.&{.` cuts the first row off the input and shapes the remaining rows into Nx3x3.
* The `"2` modifies the central verb to take the 3x3 cases.
* `10 10&#:` gives 2 decimal digits for each number giving an Nx3x2 matrix. (Getting 0s for padding was a *pain*.)
* `,"2":"0` converts the digits to ASCII (Nx3x2x1) and ravels the last column, giving Nx3x2 again as ASCII.
* `LF,~"1([,':',])/"2` inserts : between each element and appends them (Nx7) and adds a line feed per for (Nx8).
* `4(1!:2)~` prints each row.

# Answer
> 4 votes
## Haskell, 159 characters

```
v(_:x:y:z:h:m:s:t:r)=(w%x+1)&":"$z%y&":"$1%z&"\n"$v$t:r where w=y*z;(%)=mod.div(t+h*w-w+m*z+s)
v _=""
d&c=tail.(shows(d+100)c++)
main=interact$v.map read.words

```

---

* Edit: (207 -\> 200) sometimes `divMod` isn't worth it!
* Edit: (200 -\> 178) succumbed to not using the elegant `foldr` approach (which works for time systems with any number of components!)
* Edit: (178 -\> 164) inlined `f`
* Edit: (164 -\> 158) removed unnecessary parentheses
* Edit: (158 -\> 160) fixed a bit introduced three edits ago: hours are now correct again
* Edit: (160 -\> 159) dropped a call to `tail`

# Answer
> 3 votes
## Ruby, 128 chars

Shamelessly copies from the python one:

```
d=$<.read.split.map(&:to_i);d[0].times{|o|x,y,z,h,m,s,t=d[o*7+1,7];t+=z*(y*h+m)+s;puts ["%02d"]*3*':'%[(t/y/z-1)%x+1,t/z%y,t%z]}

```

# Answer
> 3 votes
## Haskell - 219 necessary characters

```
import Text.Printf
(#)=div
(%)=mod
n?d=(n-1)%d+1
e a n=mapM(\_->a)[1..n]
main=readLn>>=(e$do{
 a<-e getLine 3;
 let[x,y,z,h,m,s,t]=map read.words=<<a;
    w=y*z;e=h*w+m*z+s+t::Int
  in printf"%02d:%02d:%02d\n"(e#w?x)(e#z%y)(e%z)})

```

# Answer
> 2 votes
## Java, ~~486~~ 371 characters

Ungolfed version: http://pastebin.com/6LiTdGyi

This gives the same output as in the provided examples.

But I disagree on that behavior: a clock does not have as many numbers as there are hours in a day: it has half of them.

Meaning that if you add 3600 seconds to 12:50:12, it should print 01:50:12, not 13:50:12 (in our standard 24/60/60 system).

I handled that in my code but commented it out in my solution for it to match the examples. Of course if you consider this, then the input times could be considered ambiguous unless you add some AM/PM marker.

But in any case, the puzzle has an inconsistency: if 00 hours should be replaced by x, then hours \> (x/2) should be replaced by hours - (x/2).

Edit: Golfed version:

```
import java.io.File;import java.util.Scanner;public class U{static int i(Scanner s){return
s.nextInt();}public static void main(String[]g)throws Exception{Scanner s=new Scanner(new File(g[0
]));int n=i(s);while(0!=n--){int J=i(s),K=i(s),L=i(s),P=(i(s)*K*L+i(s)*L+i(s)+i(s))%(J*K*L);System.
out.println(String.format("%02d:%02d:%02d",(0==P/L/K%J)?J:P/L/K%J,P/L%K,P%L));}}}

```

# Answer
> 2 votes
## PHP (241 chars)

Takes input from a file passed as an argument.

```
foreach(array_chunk(array_slice(file($argv[1]),1),3)as$v){list($x,$y,$z)=split(" ",$v[0]);list($h,$m,$s)=split(" ",$v[1]);$e=($v[2]+$s+$z*($m+$h*$y))%($x*$y*$z);$s=$e%$z;$e/=$z;$m=$e%$y;$h=($e/$y)%$x;printf("%02d:%02d:%02d\n",$h?:$x,$m,$s);}

```

And ungolfed:

```
$input = array_chunk(array_slice(file($argv[1]),1),3);
foreach($input as $v){
    list($x,$y,$z)=split(" ",$v[0]);
    list($h,$m,$s)=split(" ",$v[1]);
    $t = $v[2];
    $seconds_in_day = $x * $y * $z;
    $total_elapsed = $t + $s + $m*$z + $h*$y*$z;
    $elapsed = $total_elapsed % $seconds_in_day;

    $sec = $elapsed % $z;
    $elapsed /= $z;

    $min = $elapsed % $y;
    $elapsed /= $y;

    $hours = $elapsed % $x;
    if ($hours == 0) $hours = $x;

    printf("%02d:%02d:%02d\n",$hours,$min,$sec);
}

```

And just to note, without sigils (the dollar sign), this comes out to 205 characters.

# Answer
> 2 votes
## Bash - 189 characters:

```
read n
for((i=0;i<n;i++));do
read x y z
read h m s
read t
R=$(((s+m*z+h*y*z+t)%(x*y*z)))
H=$((R/y/z))
R=$((R-H*y*z))
M=$((R/z))
printf"%02d:%02d:%02d\n"$((((H-1)%x+x)%x+1))$M$((R-M*z))
done

```

# Answer
> 1 votes
## PHP, ~~229~~ 228 characters

```
<?$v=file($argv[1]);while(++$i<$v[0]*3){list($x,$y,$z)=split(" ",$v[$i++]);list($h,$m,$s)=split(" ",$v[$i++]);$s=($e=($v[$i]+$s+$m*$z+$h*$y*$z)%($x*$y*$z))%$z;$m=($e/=$z)%$y;printf("%02d:%02d:%02d\n",($e/$y)%$x?$e%$x:$x,$m,$s);}

```

File must be passed into the script as an argument

**Ungolfed:**

```
<?php

$v = file($argv[1]); // Automatically break the file into an array by line

while(++$i < $v[0]*3){ // Loop for every three lines
  list($x, $y, $z) = explode(" ", $v[$i++]); // Break apart the first line by space
  list($h, $m, $s) = explode(" ", $v[$i++]); // Break apart the second line

  /*
    Add the starting time to the total number of seconds that have passed
    Divide by total amount of seconds in a day
  */

  $time = ($v[$i] + $s + $m * $z + $h * $y * $z) % ($x * $y * $z);

  $seconds = $time % $z;  // Get the number of seconds
  $minutes = ($time /= $z) % $y; // Remove the end amount of seconds, then get the minutes

  /*
    Remove the end amount of hours
    Determine how many hours there would be
    If the number is zero, then output the max hours
    If the number is not zero, output the amount of hours left
  */

  $hours = ($time / $y) % $x? $e % $x : $x;

  // Display the time in the correct format
  printf("%02d:%02d:%02d\n", $hours, $minutes, $seconds);
}

```

**Changelog:**

229 -\> 228: No need to set time remaining while performing division on the hours

# Answer
> 1 votes
## Bash, 139 characters

```
read n
while((n--));do
read x y z;read h m s;read t
((t+=z*(y*h+m)+s,a=(t/y/z-1)%x+1,b=t/z%y,c=t%z))
printf %02d:%02d:%02d\\n $a $b $c
done

```

# Answer
> 1 votes
## Scala 184 chars:

```
object C extends App{val r=new java.util.Scanner(System.in)
def n=r.nextInt
for(j<-1 to n;h=n;m=n;s=n;x=n;y=n;z=n;t=n;d=(x*m+y)*s+z+t){printf("%02d:%02d:%02d\n",d/(m*s)%h,d/s%m,d%s)}
}

```

In conflict to the rules, I claim, that for

```
14 15 20
1 14 0
-580

```

The output shouldn't be

```
14:00:00

```

but

```
00:00:00

```

and that's what my code produces. Please show me a clock which displays 24:00:00 on earth instead of 00:00:00 - maybe 24:59:59. Or do you expect the sequence:

```
23:59:59
24:00:00
00:00:01

```

instead of

```
23:59:59
00:00:00
00:00:01

```

# Answer
> 1 votes
# Python 2, 137 bytes

```
lambda T:["%02d:%02d:%02d"%((s/z/y%x,x)[s%x<1],s/z%y,s%z)for x,y,z,h,m,s,t in[T[i:i+7]for i in range(1,len(T),7)]for s in[s+m*z+h*y*z+t]]

```

Try it online!

Only slightly shorter than the other Python answer, but takes a different route to get there.

**Ungolfed Explanation:**

```
def f(T):
    # ignore first list element, split list into even chunks of length 7
    for i in range(1, len(T), 7):
        # get variables for sublist
        for x, y, z, h, m, s, t in [T[i:i + 7]]:
            # get total time in seconds, inside a list so that we can use list comprehension
            for s in [s + m*z + h*y*z + t]:
                # split total time into parts
                # seconds: convert seconds to minute, take remainder
                sec = s % z
                # minutes: convert seconds to minutes (discard remainder), convert minutes to hours, take remainder
                min = s / z % y
                # hours: convert seconds to minutes (discard remainder),
                #        convert minutes to hours (discard remainder),
                #        convert hours to days, take remainder
                # if seconds are evenly divisible by total hours, use number of hours in day instead ("midnight")
                hr = (s / z / y % x, x)[s % x < 1]

                print "%02d:%02d:%02d"%(hr, min, sec)

```

# Answer
> 0 votes
## Haskell (~~815~~ 624 chars non-golfed, blank lines excluded)

~~Mine prints 00:00:00 instead of 12:00:00 or similar for "midnight"-like times.~~ Edit: changed that.

```
main = readFile "in.txt" >> mapM_ print . times . map (map read . words) . tail . lines

times [] = []
times ([x,y,z]:[h,m,s]:[t]:xs) = Time x y z h m s +++ t : times xs

data Time = Time {x,y,z,h,m,s :: Int}
hr t | h t == 0 = x t | otherwise = h t

instance Show Time where show t = pad2 (hr t) ++ ':':pad2 (m t) ++ ':':pad2 (s t)

pad2 x | x < 10 = '0':show x | otherwise = show x

t +++ ss | ss < 0  = t +++ (ss + x'*y'*z') | otherwise = Time x' y' z' h' m' s'
  where (x',y',z') = (x t, y t, z t)
        (ms, s') = (s t + ss) `quotRem` z'
        (hs, m') = (m t + ms) `quotRem` y'
        (_,  h') = (h t + hs) `quotRem` x'

```

Could've abstracted a few things more, but w/e. It completely ignores the first line of the input file, and generally screams at you for improperly-formatted files.

---
Tags: code-golf, date
---


# Question
Title: Codegolf Rainbow : Fun with Integer-Arrays
## Introduction:

(Source: Wikipedia)
When we look at a rainbow it will always have the colors from top to bottom:
Red; orange; yellow; green; blue; indigo; violet

If we look at these individual rings, the red ring is of course bigger than the violet ring.
In addition, it's also possible to have two or even three rainbow at the same time.

All this above combined will be used in this challenge:

## Challenge:

Given a list of integers of exactly size 7, where each value indicates the color-particles available to form rainbows (where the largest index indicates red and the smallest index indicated violet), output the amount of rainbows that can be formed.

A single integer-rainbow has to have at least 3x violet, 4x indigo, 5x blue, 6x green, 7x yellow, 8x orange, 9x red. A second rainbow on top of it will be even bigger than the red ring of the first rainbow (including one space between them), so it will need at least 11x violet, 12x indigo, 13x blue, 14x green, 15x yellow, 16x orange, 17x red in addition to what the first rainbow uses. The third rainbow will start at 19x violet again.

**Example:**

Input-list: `[15,20,18,33,24,29,41]`
Output: `2`

Why? We have 15x violet, and we need at least 3+11=14 for two rainbows. We have 20 indigo and we need at least 4+12=16 for two rainbows. Etc. We have enough colors for two rainbows, but not enough to form three rainbows, so the output is `2`.

## Challenge rules:

* The integers in the input-array are guaranteed to be non-negative (`>= 0`).
* The input-list is guaranteed to be of size 7 exactly.
* When no rainbows can be formed we output `0`.
* Input and output format is flexible. Can be a list or array of integers of decimals, can be taken from STDIN. Output can be a return from a function in any reasonable output-type, or printed directly to STDOUT.

## Minimum amount of colors required for `n` amount of rainbows:

```
Amount of Rainbows    Minimum amount per color
0                     [0,0,0,0,0,0,0]
1                     [3,4,5,6,7,8,9]
2                     [14,16,18,20,22,24,26]
3                     [33,36,39,42,45,48,51]
4                     [60,64,68,72,76,80,84]
5                     [95,100,105,110,115,120,125]
etc...

```

## 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.
* Also, adding an explanation for your answer is highly recommended.

## Test cases:

```
Input:  [15,20,18,33,24,29,41]
Output: 2

Input:  [3,4,5,6,7,8,9]
Output: 1

Input:  [9,8,7,6,5,4,3]
Output: 0

Input:  [100,100,100,100,100,100,100]
Output: 4

Input:  [53,58,90,42,111,57,66]
Output: 3

Input:  [0,0,0,0,0,0,0]
Output: 0

Input:  [95,100,105,110,115,120,125]
Output: 5

Input:  [39525,41278,39333,44444,39502,39599,39699]
Output: 98

```

# Answer
> 9 votes
# Pyth, 14 bytes

```
thS.ef<b*+tkyy

```

Test suite!

## How?

**Algortihm**

First off, let's derive the formula this answer is based off. Let's call the function that gives the necessary amount of colour particles \\$C(n, i)\\$, where \\$n\\$ is the number of layers and \\$i\\$ is the index of the colour, 0-based. First, we note that for the \\$n^\text{th}\\$ layer alone (where \\$n\\$ is 1-indexed, in this case), we need \\$L(n, i)=i+3+8(n-1)\\$ colour particles. Keeping this in mind, we sum the results of each \\$L(k, i)\\$ for each layer \\$k\\$:

$$C(n, i)=\color{red}{\underbrace{(i+3)}\_{1^\text{st} \text{ layer}}} + \color{blue}{\underbrace{(i+3+8)}\_{2^\text{nd} \text{ layer}}}+\cdots + \color{green}{\underbrace{\[i+3+8(n-1)\]}\_{n^\text{th} \text{ layer}}}$$ $$C(n, i)=(i+3)n+8\left(0+1+\cdots +n-1\right)$$ $$C(n, i) = (i+3)n+8\cdot\frac{(n-1)n}{2}=(i+3)n+4n(n-1)$$ $$C(n, i)=n(i+3+4n-4)\implies \boxed{C(n,i)=n(4n+i-1)}$$

Therefore, we now know that the maximum number of possible layers, call it \\$k\\$, must satisfy the inequality \\$C(k, i) \le I\_i\\$, where \\$I\_i\\$ is the \\$i^\text{th}\\$ element of the input list.

**Implementation**

This implements the function \\$C\\$, and iterates (`.e`) over the input list, with \\$k\\$ being the index (0-based) and \\$b\\$ being the element. For each value, the program searches the first positive integer \\$T\\$ for which \\$b\<C(T, i)\\$ (the logical negation of \\$C(T, i)\le b\\$, the condition we deduced earlier), then finds the minimum result and decrements it. This way, instead of searching for the highest integer that *does* satisfy a condition, we search for the lowest that *does not* and subtract one from it to make up for the offset of 1.

# Answer
> 3 votes
# Python 2, ~~64~~ 61 bytes

```
lambda l:min(((16*v+i*i)**.5-i)//8for i,v in enumerate(l,-1))

```

Try it online!

---

Each colour of the rainbow uses `(3+i)+n*8` for layer `n` and color `i`(0=violet, etc.)

The total for x layers is therefore: `(3*i)*x + 8*x*(x+1)`.

We simply solve for n, and take the minimum value.

---

Saved:

* -3 bytes, thanks to ovs

# Answer
> 3 votes
# 05AB1E, ~~18~~ ~~17~~ 16 bytes

-1 byte thanks to Magic Octopus Urn

```
[ND4*6Ý<+*¹›1å#N

```

Try it online!

The amount of colour needed for **n** rainbows is **n(4n + \[-1, 0, 1, 2, 3, 4, 5\])**.

# Answer
> 2 votes
# JavaScript (ES6), 49 bytes

```
f=(a,n)=>a.some((v,k)=>v<4*n*n-~-k*n)?~n:f(a,~-n)

```

Try it online!

### How?

The number \\$P\_{(n,k)}\\$ of color particles required to generate \\$n\\$ times the \\$k\\$-th color is:

$$P\_{(n,k)}=n(4n+(k-1))=4n^2+(k-1)n$$

We recursively try all values of \\$n\\$ until at least one entry \\$v\_k\\$ in the input array is lower than \\$P\_{(n,k)}\\$.

But for golfing purposes, we start with `n === undefined` and use negative values of `n` afterwards. The first iteration is always successful because the right side of the inequality evaluates to `NaN`. Therefore, the first meaningful test is the 2nd one with `n == -1`.

# Answer
> 1 votes
# Jelly, 18 bytes

```
Ṁµ×4+-r5¤×)⁸<Ẹ€¬TṪ

```

Try it online!

Uses the explanation in Okx's 05AB1E answer.

# Answer
> 1 votes
# Excel VBA, 78 bytes

Anonymous function that takes input from the range of `[A1:G1]` and outputs to the VBE immediate window.

```
[A2:G999]="=A1-(COLUMN()+8*ROW()-14)":[H:H]="=-(MIN(A1:G1)<0)":?998+[Sum(H:H)]

```

# Answer
> 1 votes
# Charcoal, 21 bytes

```
Ｉ⌊ＥＡ÷⁻Ｘ⁺Ｘ⊖κ²×¹⁶ι·⁵⊖κ⁸

```

Try it online! Link is to verbose version of code. Explanation: Directly calculates the number of rainbows possible with each colour with a formula I derived independently but turns out to be the same as @TField's formula.

```
   Ａ                   Input array
  Ｅ                     Map over values
          κ             Current index
         ⊖              Decrement
        Ｘ  ²            Square
               ι        Current index
            ×¹⁶         Multiply by 16
       ⁺                Add
      Ｘ         ·⁵      Square root
                   κ    Current index
                  ⊖     Decrement
     ⁻                  Subtract
    ÷               ⁸   Integer divide by 8
 ⌊                      Take the maximum
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 1 votes
# JavaScript (Node.js), 54 bytes

*Port of @TFeld answer*

```
_=>Math.min(..._.map((a,i)=>((16*a+--i*i)**.5-i)/8))|0

```

Try it online!

# Answer
> 1 votes
# Jelly, 14 bytes

This was hard!

```
Ṃ+9s8Ṗ‘+\>Ż§ỊS

```

A monadic Link accepting a list of seven integers which yields an integer, the number of rainbows possible.

**Try it online!** Or see the test-suite.

### How?

Unfortunately any naive method seems to take 16 bytes, one such method is `Ṃɓ_J×¥H÷‘H<¬Ȧð€S`, however it turns out the method used here is much more efficient as well as shorter!

This method builds more than enough rainbow stacks as particle counts, **including ultra-violet bands**, and adds up 1 for each stack which is possible.

The test for it being possible is to check that there is only a single band NOT possible given we need some ultra-violet band particles but were provided zero.

```
Ṃ+9s8Ṗ‘+\>Ż§ỊS - Link list of integers    e.g. [0,0,0,0,0,0,0]        or [17,20,18,33,24,29,41]
Ṃ              - minimum                       0                         17
 +9            - add nine                      9                         26
   s8          - split into eights             [[1,2,3,4,5,6,7,8],[9]]   [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19,20,21,22,23,24],[25,26]]
     Ṗ         - discard the rightmost         [[1,2,3,4,5,6,7,8]]       [[1,2,3,4,5,6,7,8],[9,10,11,12,13,14,15,16],[17,18,19,20,21,22,23,24]]
      ‘        - increment (vectorises)        [[2,3,4,5,6,7,8,9]]       [[2,3,4,5,6,7,8,9],[10,11,12,13,14,15,16,17],[18,19,20,21,22,23,24,25]]
               -   (single rainbow counts, including ultra-violet bands, ready to stack)
       +\      - cumulative addition           [[2,3,4,5,6,7,8,9]]       [[2,3,4,5,6,7,8,9],[12,14,16,18,20,22,24,26],[30,33,36,39,42,45,48,51]]
               -   (stacked rainbow counts, including ultra-violet bands)
          Ż    - zero concatenate              [0,0,0,0,0,0,0,0]         [0,17,20,18,33,24,29,41]
               -   (we got given zero ultra-violet band particles!)
         >     - greater than? (vectorises)    [[1,1,1,1,1,1,1,1]]       [[1,0,0,0,0,0,0,0],[1,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1]]
               -   (always a leading 1 - never enough particles for the ultra-violet band)
           §   - sum each                      [8]                       [1,1,8]
               -   (how many bands we failed to build for each sacked rainbow?)
            Ị  - insignificant? (abs(X)<=1?)   [0]                       [1,1,0]
               -   (1 if we only failed to build an ultra-violet band for each sacked rainbow, 0 otherwise)
             S - sum                           0                         2
               -   (the number of rainbows we can stack, given we don't see ultra-violet!)

```

# Answer
> 1 votes
# 05AB1E, 14 bytes

```
žv*āÍn+tā-Ì8÷ß

```

Try it online!

A closed-form solution which does not require additional looping rather than the map. This works by adapting my Pyth's answer's formula to match 05AB1E's indexing convention, then solving for \\$n\\$, which happens to match TFeld's algorithm.

### Pyth algorithm ⟶ 05AB1E Algorithm

There are *many* methods one can try for solving this challenge in 05AB1E, so I tried a couple of them and this turned out to be the shortest. Adapting the aforementioned formula from my Pyth answer, keeping in mind that 05AB1E used 1-indexing, we can construct our function as follows:

$$C(n,i)=n(i+2)+4n(n-1)$$

Setting it equal to the element of the input (\\$I\\$) at index \\$i\\$ and writing it in standard (quadratic) polynomial notation, we have:

$$4n^2+n(i-2)-I\_i=0$$

Note that this equality is not precise (but I currently don't know of a way to state this more formally) and that the solutions to this equation will yield floating-point numbers, but we fix this by using floor division rather than precise division later on. Anyway, to continue on with our argument, most of you are probably very familiar with the solutions of such an equation, so here we have it:

$$n\_{1, 2}=\frac{2-i\pm\sqrt{(i-2)^2+16I\_i}}{8}$$

As \\$I\_i\\$ is always positive, \\$\sqrt{(i-2)^2+16I\_i}\ge i-2\\$, so the "\\$-\\$" case doesn't make much sense, because that would be either \\$2-i-i+2=4-2i\\$, which is negative for \\$i\ge 2\\$ or \\$2-i-2+i=4\\$, which is constant. Therefore, we can conclude that \\$n\\$ is given by:

$$n=\left \lfloor\frac{2+\sqrt{(i-2)^2+16I\_i}-i}{8}\right \rfloor$$

Which is exactly the relation that this answer implements.

# Answer
> 1 votes
# C++, ~~127~~ 125 bytes

Shaved off 2 bytes thanks to Kevin Cruijssen.

```
#include<cmath>
int f(int x[7]){size_t o=-1;for(int c=0,q;c<7;c++,o=o>q?q:o)q=(std::sqrt(--c*c-c+16*x[++c])-c+1)/8;return o;}

```

Try it online!

The function takes a C-style array of seven ints and returns an int.

The algorithm is pretty straightforward (and have already been described a number of times previously, so here is one more description, mostly for my own viewing pleasure). Let \\$c\\$ be the color index (\\$0\le c\le6\\$), so the required number of particles to form \\$n\\$-th \\$(n\ge1)\\$ rainbow part of that color is \\$y\_c(n)=(c+3)+8(n-1)\\$, and the total amount of particles to form \\$n\\$ rainbow parts of the color is then \\$Y\_c(n)=\sum\_{k=1}^{n}y\_c(k)=n(c+3)+\frac{8n(n-1)}{2}\\$. Now we have a system of inequalities \\$x\_c\ge Y\_c(n)\\$ (where \\$x\_c\\$ is the elements of input array), which gives us a set of upper bounds on \\$n:\\$ $$n\le\frac{-(c-1) + \sqrt{(c-1)^2 + 16x\_c}}{8}$$.

What is left is just iterate over \\$x\_c\\$ and find the minimum.

Explanation:

```
#include <cmath> // for sqrt

int f (int x[7])
{
     // Note that o is unsigned so it will initially compare greater than any int
     size_t o = -1;
     // Iterate over the array
     for (int c = 0; c < 7; c++)
     {
         // calculate the bound
         int q = c - 1;
         q = (std::sqrt (q * q + 16 * x[c]) - q) / 8;

         // if it is less than previously found - store it
         o = o > q ? q : o;
     }
     return o;
 }

```

---
Tags: code-golf, number, integer
---


title: Watch the bookie win

text:
# Question
Title: Watch the bookie win
When you roll a die, you have a 6:1 chance of any given option.

There's a bookmaker taking bets on die rolls. He owns £20 at the start of the game.

The bookmaker offers odds of 4:1, but gamblers take it, because there's money on offer.

There are 10 gamblers. A, B, C, D, E, F, G, H, I, and J. Each gambler owns 10 pounds sterling.

Each round, the 10 gamblers each bet £1 on a die roll, if they have any money left.

* If they win their bet, £4 is transferred from the bookmaker to the gambler.
* If they lose, £1 is transferred from the gambler to the bookmaker.

The game ends in either of these conditions:

* The bookmaker runs out of money, or is in debt.
* All of the gamblers have run out of money.

We should see the result presented as a series of tables, like so:

```
Turn 1
Roll: 2

|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 20     | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 | 10 |
| Bet            | n/a    | 1  | 3  | 2  | 1  | 2  | 4  | 6  | 5  | 2  | 4  |
| Balance change | -2     | -1 | -1 | +3 | -1 | +3 | -1 | -1 | -1 | +3 | -1 |
| End money      | 18     | 9  | 9  | 13 | 9  | 13 | 9  | 9  | 9  | 13 | 9  |

Turn 2
Roll: 4

|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 18     | 9  | 9  | 13 | 9  | 13 | 9  | 9  | 9  | 13 | 3  |
| Bet            | n/a    | 1  | 2  | 3  | 4  | 5  | 6  | 1  | 2  | 3  | 4  |
| Balance change | +2     | -1 | -1 | -1 | +3 | -1 | -1 | -1 | -1 | -1 | +3 |
| End money      | 20     | 8  | 8  | 12 | 8  | 12 | 8  | 8  | 8  | 12 | 12 |

```

When a gambler runs out of money, they can't bet any more. Their bet is 0.

turn 20 roll: 5

```
|                | Bookie | A  | B  | C  | D  | E  | F  | G  | H  | I  | J  |
| Start money    | 180    | 3  | 1  | 12 | 4  | 0  | 1  | 3  | 6  | 23 | 1  |
| Bet            | n/a    | 1  | 2  | 3  | 4  | 0  | 6  | 1  | 2  | 3  | 4  |
| Balance change | +2     | -1 | -1 | -1 | +3 | 0  | -1 | -1 | -1 | -1 | +3 |
| End money      | 20     | 8  | 8  | 12 | 8  | 0  | 8  | 8  | 8  | 12 | 12 |

```

---

Write some code to model this game, and display the results in a table:

* Use any language
* The gamblers can change their bet each turn, always bet on the same number, all bet on the same number. As long as each turn they bet on one number from 1 to 6.
* The die roll must be a random integer from 1 to 6. Use a typical, vernacular definition of random.
* The end money from one turn is the start money of the next turn.
* The balance change for the bookie is the sum of the other balance changes.
* Each turn your program should output:
    + Which turn we are on
    + The resulting die roll
    + The starting balance, die roll, balance change, and ending balance for the bookie and all ten gamblers, as an ascii table.
* Attempt to do so in the fewest bytes.

# Answer
> 8 votes
# JavaScript (Node.js), ~~548~~ ~~516~~ ~~511~~ ~~485~~ ~~453~~ ~~397~~ ~~396~~ ~~392~~ ~~372~~ ~~325~~ ~~323~~ 260 bytes

```
f=(i=!(b=20,p=10))=>b*p>0?`T:${++i} R:${(r=0|Math.random()*6)+1}
|   |Book|A |B |C |D |E |F |G |H |I |J |
|Stt${(d=(n,s)=>`|${n}`.padEnd(5)+`|${s}`.padEnd(3).repeat(10)+`|
`)(b,p)}|Bet${d('n/a',1)}|Chg${d(u=r?'+10':-40,v=r?-1:'+4')}|End`+d(b+=+u,p+=+v)+f(i):''

```

Try it online!

*-32 something bytes by shortening row labels. Also fixed the dice roll being 0-5, not 1-6*
*-5 bytes by compacting output format*
*-26 bytes because padding*
*-32 bytes because whitespace is the devil*
*-56 bytes thanks to ASCII-only and Luis Felipe in chat*
*-1 byte because `return x` doesn't need to be on a new line*
*-4 bytes thanks to some small refactors from ASCII-only*
*-20 bytes thanks to more collaboration in chat and some changes by Kevin Cruijssen*
*-47 bytes because `y` was the devil and ASCII-only performed an exorcism*
*-2 bytes because ASCII-only is a golfing machine*
*-63 bytes thanks to the work of several people in the comments*

The golf I took was calculated, but man am I bad at golf.

Almost looks like python rather than JS because where possible I used newlines in place of semicolons for readability.

All gamblers always bet on 1, so we only need to store 1 gambler balance (`p`), the bookie's balance is `b`.

## Explanation time

I need to rewrite the explanation to match the 260 byte version, but check the revision history for the lengthy explanation of the 323 byte version.

# Answer
> 3 votes
# Charcoal, 248 bytes

```
≔²⁰θ≔ＥχχηＷ∧›θ⁰⌈η«Turn: ＩＬ⊞Ｏυω⸿Roll: ≔⊕‽⁶ζＩζ”{⧴&ＤCＺJＷ›B↨⊘ＫBgU→≦”⪫…αχ |  ﹪ |⸿| Start  |%7d |θ⪫Ｅη◧Ｉκ³ |≔Ｅη∧κ⊕‽⁶ε”{➙∧➙⌈℅⎇/s?↨Vp2S>”⪫ε |  ≔⁻ＬΦεκ×⁴ＬΦε⁼κζδ |⸿| Change |◧⁺…+›δ⁰δ⁷ | ⪫Ｅε⎇⁼κζ+3⎇κ-1⁺ ⁰ | ≦⁺δθ﹪ |⸿| End    |%7d |θＵＭη⁻κ∧§ελ∨¬⁼§ελζ±³⪫Ｅη◧Ｉκ³ |¦ |⸿⸿

```

Try it online! Link is to verbose version of code. Explanation:

```
≔²⁰θ

```

The bookie starts with £20.

```
≔Ｅχχη

```

Create an array of 10 £10s for the gamblers.

```
Ｗ∧›θ⁰⌈η«

```

Repeat the rest of the program while the bookie and at least one gambler have any money left.

```
Turn: ＩＬ⊞Ｏυω

```

Print the current turn by pushing a value to the predefined empty list and taking the resulting length.

```
⸿Roll: ≔⊕‽⁶ζＩζ

```

Generate and print the next roll.

```
”{⧴&ＤCＺJＷ›B↨⊘ＫBgU→≦”⪫…αχ

```

Print the header row.

```
 |  ﹪ |⸿| Start  |%7d |θ⪫Ｅη◧Ｉκ³ |

```

Print the starting balances.

```
≔Ｅη∧κ⊕‽⁶ε

```

Generate the 10 bets (or 0 if the gambler has no money left).

```
”{➙∧➙⌈℅⎇/s?↨Vp2S>”⪫ε |

```

Print the bets.

```
≔⁻ＬΦεκ×⁴ＬΦε⁼κζδ

```

Calculate the bookie's change in balance.

```
 |⸿| Change |◧⁺…+›δ⁰δ⁷ | ⪫Ｅε⎇⁼κζ+3⎇κ-1⁺ ⁰ |

```

Print the bookie's and gamblers' changes in balance.

```
≦⁺δθ﹪ |⸿| End    |%7d |θ

```

Update and print the bookie's balance.

```
ＵＭη⁻κ∧§ελ∨¬⁼§ελζ±³⪫Ｅη◧Ｉκ³ |¦ |⸿⸿

```

Update and print the gamblers' balances.

# Answer
> 2 votes
# Kotlin, ~~468~~ 432 bytes

I'm definitely going to try this another way as I'd like it to be around 300. However, it works. Player 1 wins by magically always picking the winning number.
-36 bytes for various golfs I missed last night including @Mayube's fixed bet on 1,

```
{var o=""
val n=Random()
val m=Array(11){10}
m[0]=20
var t=0
val f={d:Int->o+="%3d|".format(d)}
while(m[0]>0){val b=Array(11){1}
b[1]=n.nextInt(6)+1
val c=Array(11){when{it<1||m[it]<1->0
b[1]==b[it]->3
else->-1}}
o+="\nT:${++t} R:${b[1]}\n|   |Bok|"
('A'..'J').map{o+=" $it |"}
o+="\n|Stt|"
m.map{f(it)}
o+="\n|Bet|n/a|"
(1..10).map{f(b[it])
c[0]-=c[it]}
o+="\n|Chg|"
(0..10).map{f(c[it])
m[it]+=c[it]}
o+="\n|End|"
m.map{f(it)}}
o}

```

Try it online!

# Answer
> 2 votes
# **R 417 bytes**

```
g=function(){s=sample
d=10
m=t(matrix(c(20,rep(d,d),NA,s(6,d,T)),11,4,di=list(c("Book",LETTERS[1:d]),c("Stt","Bet","Chg","End"))))
i=1
u=which
while(m[1,1]!=0){
if(m[1,1]==120)break
w=s(6,1)
l=m[1,]!=0
o=m[2,]==0
m[3,u(o&l)]=3
m[3,u(!o&l)]=-1
m[3,u(m[1,]==0)]=0
m[3,1]=-sum(m[3,2:11],na.rm=T)
m[4,]=colSums(m[c(1,3),])
print(kable(m,ca=paste0("T:",i," R:",w),format="pandoc"))
m[1,]=m[4,]
m[2,]=c(NA,s(6,d,T))
i=i+1}}

```

**Explanation:**

*I was going to post a while ago, but my first attempt was at about 600, after some effort, I whittled it down to 500. After more research, I slowly got down to this result. I'm open to advice regarding better methods.*

**NOTE:** R has a package known as knitr which utilizes the kable function to create tables with various formats (Latex, HTML, pandoc, etc). Each player makes a random guess every turn. Most games end between 26 and 200 or so turns, with the bookie winning every game. Also, variable name choice has little reasoning, I just tried to avoid using builtins as variable names.

```
g=function(){s=sample          # Abbreviate sample function
d=10                           # Store 10
m=t(matrix(c(20,rep(d,d),NA,s(6,d,T)),11,4,di=list(c("Book",LETTERS[1:d]),c("Stt","Bet","Chg","End"))))
                               # Creates a 11x4 matrix, populates it, names it's columns and rows, and transposes it.
i=1                            # Turn Counter
u=which                        # Abbreviate the which function that tests values to be equivalent to a chosen values
while(m[1,1]!=0){              # While loop with condition on the bookie not having 0 pounds
if(m[1,1]==120)break           # Loop stops if bookie reaches 120 pounds, total
w=s(6,1)                       # Bookie Dice Roll/Winning Die Value
l=m[1,]!=0                     # Check if total pounds of each player equals 0
o=m[2,]==w                     # Check if players choices matches the winning roll
m[3,u(o&l)]=3                  # If guess is correct, and current wages is not 0, store 3
m[3,u(!o&l)]=-1                # If guess is incorrect, and current wages is not 0, store -1
m[3,u(m[1,]==0)]=0             # If current wages is 0, store 0
m[3,1]=-sum(m[3,2:11],na.rm=T) # Add up players totals to get the change to the bookies total
m[4,]=colSums(m[c(1,3),])      # Add the old total to the change
print(kable(m,ca=paste0("T:",i," R:",w),format="pandoc"))   #Print the table with title
m[1,]=m[4,]                    # Store last row in first row
m[2,]=c(NA,s(6,d,T))           # Store new guesses in second row
i=i+1}}                        # Add to the turn counter

```

# Answer
> 1 votes
# C (gcc), 407 406 397 bytes

Each of the gamblers chooses a random number and then always bets on that value.

Thanks to ceilingcat for the suggestions.

```
#define l(a,b)for(i=11,a;i--;b)
#define p printf
#define q p("%d"s,a[i])
#define z(a)p("\n| "#a s)
#define s"\t| "
a[11],b[11];r,t,i,j,k;f(){l(0,b[i]=i?rand()%6:0)a[i]=10*-~!i;for(t=0;++t;){l(p("\n\nTurn %d\tRoll: %d\n|"s,t,r=rand()%6),p(i?"%c"s:"Book"s,75-i));l(z(Start),q);l(z(Bet),p(i?"%d"s:"-"s,1+b[i]));l(k=!z(Chg),p("%+d"s,i?j:k))k-=j=i?4-5*b[i]!=r:0,*a-=j,a[i]+=j;l(z(End),a[i]||(t=-1))q;}}

```

Try it online!

---
Tags: code-golf, game, probability-theory
---


# Question
Title: Scoring 6,5,4 (AKA Ship, Captain, and Crew)
Inspired and looted from this dice challenge by Arnauld

# Input

You are given a 5x1 or 1x5 (your choice) dice matrix which consist of binary 3x3 sub-matrices.

# Goal

Given a valid dice matrix, you are to score it using the rules of 6,5,4 which are as follows:

* If the roll contains 6,5,4, add the other two dice together and that is your score. E.g. 4,X,5,6,Y = X+Y
* Otherwise, the score is 0. E.g. 5,5,5,4,1 = 0

Wiki article for the game

## Dice patterns

$$\begin{align} &1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0} &&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\ &3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0} &&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\ &5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1} &&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1} \end{align}$$

# Rules

* The matrix is guaranteed to only contain valid faces but will include the 2,3 and 6 permutations. You can also take it in either orientation in whatever way is convenient. Please state the chosen orientation in your answer.
* Output the calculated score
* Standard Loopholes are forbidden
* This is .

# Examples

```
// 2,5,2,4,6: Output should be: 4
[ [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ],
  [ 1,0,1 ],
  [ 0,1,0 ],
  [ 1,0,1 ],
  [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ],
  [ 1,0,1 ],
  [ 0,0,0 ],
  [ 1,0,1 ],
  [ 1,1,1 ],
  [ 0,0,0 ],
  [ 1,1,1 ] ]

// 1,6,2,4,6: Output should be: 0
[ [ 0,0,0, 1,0,1, 1,0,0, 1,0,1, 1,1,1  ],
  [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0  ],
  [ 0,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1  ] ]

// 5,6,6,4,6: Output should be: 12
[ [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1  ],
  [ 0,1,0, 1,0,1, 0,0,0, 0,0,0, 0,0,0  ],
  [ 1,0,1, 1,0,1, 1,1,1, 1,0,1, 1,1,1  ] ]

// 3,3,4,5,6: Output should be: 6
[ [ 0,0,1, 1,0,0, 1,0,1, 1,0,1, 1,1,1  ],
  [ 0,1,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0  ],
  [ 1,0,0, 0,0,1, 1,0,1, 1,0,1, 1,1,1  ] ]

// 2,5,2,5,6: Output should be: 0
[ [ 0,0,1, 1,0,1, 1,0,0, 1,0,1, 1,1,1  ],
  [ 0,0,0, 0,1,0, 0,0,0, 0,1,0, 0,0,0  ],
  [ 1,0,0, 1,0,1, 0,0,1, 1,0,1, 1,1,1  ] ]

```

# Answer
# 05AB1E, 15 bytes

```
3ôO<O©3LsK_P®O*

```

Try it online! or Check out a test suite!

Uses the same trick as Chas Brown and Lynn use: decrementing each integer in each 3x3 sub-matrix rather than subtracting 15 at the end. Expects input in column format.

### How it works

```
3ôO<OD3LsK_PsO* – Full program.
3ô              – Split the input in 3x3 matrices representing dice faces.
  O<O           – Sum each, subtract one and sum each again.
                  This works because after the first O there are 3 elements in each
                  list and there are 5 lists in total, so 3 * 5 = 15 = 4 + 5 + 6.
     ©          – Copy this to the register.
      3LsK      – Push [1, 2, 3] and perform set subtraction. In this scenario, we
                  have already subtracted 3 from each list, so [1, 2, 3] represent
                  the actual dice values [4, 5, 6]. If the resulting list is empty,
                   that means that those values do exist in our roll. Therefore:
          _P    – Produce a list of zeros of that length and take the product
                  (4,5,6 isn't in the dice roll if the list is empty
                  and this method assures that in this case the product is 1, else 0)
            ®O* – Sum what's in the register and multiply by that.

```
> 4 votes

# Answer
# Perl 6, ~~48~~ 46 bytes

*Thanks to Ramillies for -2 bytes*

```
{(^3+4⊂.flat.rotor(9)>>.sum)*(.flat.sum-15)}

```

Try it online!

An anonymous code block that takes the matrix vertically and returns an integer.

### Explanation:

```
{                                          } # Anonymous code block
                             (.flat.sum-15)  # Get the total sum of the array minus 15
                            * # Multiply by:
 (^3+4⊂                    )    # Whether 4,5,6 is a sub-array of:
       .flat.rotor(9)>>.sum     # The value of each dice

```
> 3 votes

# Answer
# Python 2, 81 bytes

```
f=lambda a,r=[]:a and f(a[3:],r+[sum(sum(a[:3],[]))-3])or({1,2,3}<=set(r))*sum(r)

```

Try it online!

All input is expected to be in the column form.
> 3 votes

# Answer
# Jelly, 14 bytes

```
s3§’§µ3Rœ-⁸ṆaS

```

Try it online!

Accepts a column of dice.

```
                  With the input (a 15×3 binary matrix):
s3                 Split into threes: now we have 5 dice, each a 3×3 matrix.
  §                Sum-each. Now we have a list of triples.
   ’               Decrement: turn each triple [x,y,z] into [x−1,y−1,z−1].
    §              Sum-each. Now we have a list of dice pip sums minus 3.
     µ            With these sums X:
      3Rœ-⁸        Subtract them from {1, 2, 3} as a multiset.
           Ṇ       Is the result empty? (This means {1, 2, 3} ⊆ X.)
            aS     If so, yield sum(X). Else the result stays 0.

```

Just like Chas Brown’s Python answer, this offsets each dice value by −3 so that we don’t need to subtract 15 (4+5+6) from the very last sum.
> 3 votes

# Answer
# MATL, 12 bytes

```
9es3-I:ymp*s

```

Try it online!

Takes input in horizontal orientation as a 3x15 matrix. @Chas Brown's trick of subtracting 3 early (instead of 15 later) saved multiple bytes in different ways.

```
9e      % reshape input to have 9 rows - each dice matrix is linearized into a column
s       % sum each column (to get dice values)
3-      % subtract 3 from each value, let's call this array A
I:      % form range 1 to 3
y       % bring a copy of array A to the top of stack
m       % check if each of 1, 2, 3 are members of A
        %  returns a logical array of 3 boolean values
p       % product of that result - 0 if any were not members, 1 if they all were
*       % multiply the original array A by this result
s       % sum

```
> 3 votes

# Answer
# Brachylog, 23 22 bytes

```
+ᵐ-₁ᵐḍ₅+ᵐJo⊇~⟦₁3∧J+|∧0

```
* +3 bytes but prints out 0 instead of false if no 4,5,6 (Fatalize)
* -2 4 bytes (sundar)

One of my first branchylog programs. Can probably be golfed more. Prints false if there is no 4,5,6. idk how to make it output 0.

Try it online!
> 3 votes

# Answer
# , 56 bytes

```
function(m)sum(x<-by(c(m),0:44%/%9,sum)-3)*all(1:3%in%x)

```

Try it online!

* -6 bytes thanks to JayCe
* -1 byte thanks to Giuseppe
> 3 votes

# Answer
# 05AB1E, ~~30~~ ~~29~~ 22 bytes

```
3ôOOJ456vyõ.;}Dg<iSOë0

```

Takes the dice-matrices below each other.

Try it online or verify all test cases.

**Explanation:**

```
3ô              # Split into sub-lists of 3, so we now have our dices
                #  i.e. [[A],[B],[C],[D],[E],[F],...] → [[[A],[B],[C]],[[D],[E],[F]],...]
  OO            # Sum each row, and then sum the total
                #  i.e. [[0,0,1],[0,0,0],[1,0,0]] → [1,0,1] → 2
    J           # Join everything together to a single string
                #  [5,4,2,5,6] → '54256'
     456v    }  # For each `y` in [4,5,6]:
         yõ.;   #  Replace the first occurrence with an empty string
                #  i.e. '54256' → '52'
D               # Duplicate the result
 g              # Take the length
                #  i.e. '52' → 2
  <i            # If the length is exactly 2 (and thus we've successfully removed [4,5,6]):
    SO          #  Split the string into digits again, and sum them as result
  ë             # Else:
    0           #  The result is 0 instead

```
> 2 votes

# Answer
# Pyth, 20 bytes

```
*-ssQ15}j456TySsMc5s

```

Expects input as a column of dice (as in test case 1). Try it online here, or verify all test cases at once here.

```
*-ssQ15}j456TySsMc5sQ   Implicit: Q=eval(input()), T=10
                        Trailing Q inferred
                   sQ   Flatten input into a single array
                 c5     Chop into 5 pieces
               sM       Take the sum of each piece
              S         Sort
             y          Take the power set
       }                Does the above contain...
        j456T           ... [4,5,6]? 1 if so, 0 otherwise <a>
  ssQ                   Deep sum of input (total pips)
 -   15                 Subtract 15 <b>
*                       Multiply <a> and <b>, implicit print

```
> 2 votes

# Answer
# JavaScript (ES6), 78 bytes

Takes input as a column of dice.

```
a=>!(a+0).replace(/.{18}/g,s=>(t+=n=s.split`1`.length,a|=1<<n),t=-20)|a>223&&t

```

Try it online!

### How?

By doing `a + 0`, we implicitly flatten and coerce the input array to a string and add a trailing `"0"`, which gives exactly **5x18 = 90** characters.

For instance, the first test case leads to:

```
0,0,1,0,0,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,1,0,0,0,1,0,1,1,1,1,0,0,0,1,1,10
\____dice #1____/ \____dice #2____/ \____dice #3____/ \____dice #4____/ \____dice #5____/

```

For each dice substring **s** of 18 characters, we compute the number **n** of pips **\+ 1** and we update the total number of pips **t** with:

```
t += n = s.split`1`.length

```

We re-use the input array **a** as a bitmask to keep track of each dice that was encountered at least once:

```
a |= 1 << n

```

If the roll contains at least one **4**, one **5** and one **6**, the bitmask **a** will have the following bits set:

```
11100000 (224 in decimal)

```

We test this by doing `a > 223`. If successful, we return **t**. Because we count one extra pip for each dice and because we don't want to count **4+5+6** in the result, **t** is initialized to **-(5 + (4+5+6)) = -20**.
> 2 votes

# Answer
# Dyalog APL, ~~28~~ 27 bytes

```
{+/⍵×∧/∨/⍉⍵∘.=⍳3}¯3+(+/¨,¨)

```

Try it online!

Takes a 1x5 matrix of 3x3 dice matrices as input.

`+/¨,¨` adds up the pip values of each of the dice. Then subtract 3, use `∨/⍉⍵∘.=⍳3` to check if there is at least one instance each of (1, 2, 3), AND the results together with `∧/` and multiply the result (0 or 1) by the sum of the adjusted dice values (`+/⍵`).
> 2 votes

# Answer
# Retina 0.8.2, 45 bytes

```
¶

M!`.{9}
%M`1
O`
¶

G`4.*5.*6
.
$*
1{15}

1

```

Try it online! Takes vertical dice. Explanation:

```
¶

M!`.{9}

```

Reshape the dice into 5 individual rows.

```
%M`1

```

Get the values of each row.

```
O`

```

Sort them into order.

Join them into a single string.

```
G`4.*5.*6

```

Ensure that the three required dice are present.

```
.
$*

```

Convert each die to unary.

```
1{15}

```

Subtract the matching 4, 5 and 6.

```
1

```

Sum and convert to decimal.
> 1 votes

# Answer
# Jelly, 18 bytes

```
s3§§µṬṚḄ>55×S_15»0

```

A monadic link

**Try it online!**
> 1 votes

# Answer
# Octave, 54 bytes

```
@(M)sum(prod(ismember(1:3,v=sum(reshape(M,9,5))-3))*v)

```

Try it online!

Port of my MATL answer.
> 1 votes

# Answer
# Ruby, 78 bytes

```
->a{s=->x{x.flatten.sum};t=4,5,6;q=a.each_slice(3).map(&s);(t&q==t)?s[a]-15:0}

```

Try it online!
> 1 votes

---
Tags: code-golf, array, binary-matrix
---