Starting from n=2 dice:

  • Roll n dice, with each number 1 to 6 equally likely on each die.
  • Check if their sum equals the most probable sum for n dice, that is 3.5*n.
    • If they're equal, terminate.
    • Otherwise, print n, and repeat from the start with n+2 dice

Your code doesn't have to do this procedure exactly, but should give random output probabilistically equivalent to it, based on our definition of randomness.

Your program should output all of the numbers on their own line; for example, if the program got up to 8 dice and rolled the most probable number with 8 dice, the output would be:


Example Run

On 2 dice, 7 is the most probable sum. Let's say the numbers rolled were 2 and 3. Then, you would print 2.

On 4 dice, 14 is the most probable sum. Let's say the numbers rolled were 3, 4, 2, and 5. Then, the sum is 14, so the program would terminate here.

The final output in this case is "2".


  • \$\begingroup\$ This answer, as it stands, is very unclear. Is there input, or is it meant to generate the output from no input as a loop? Is there any randomness? I don't seem to see any randomness involved. \$\endgroup\$ – HyperNeutrino Jun 13 '17 at 1:59
  • \$\begingroup\$ By the way, welcome to PPCG! :) \$\endgroup\$ – HyperNeutrino Jun 13 '17 at 1:59
  • \$\begingroup\$ Thank you, Sorry I am very new to this. What would make it more clear? There is no input, you are supposed to start with one die and work your way up as high as you can. \$\endgroup\$ – zoecarver Jun 13 '17 at 2:01
  • \$\begingroup\$ @pudility So if I understand correctly, I am supposed to keep outputting 2, 4, 6, 8, ... an roll that many dice each time until I hit the most probable number for that iteration? \$\endgroup\$ – HyperNeutrino Jun 13 '17 at 2:03
  • 5
    \$\begingroup\$ Thank you for taking the time to edit your challenge based on our feedback! For the record, we have a place where you can post challenges to work out some of the details before posting: the sandbox. \$\endgroup\$ – FryAmTheEggman Jun 13 '17 at 2:12

28 Answers 28


Python 2, 70 bytes

from random import*
while eval("+randrange(6)-2.5"*n):print n;n+=2

Try it online!

The trick is to compute the sum by evaling a string the looks like


with n copies of the expression concatenated. The randrange(6) outputs a random number from [0,1,2,3,4,5], which is shifted down by 2.5 to have average of 0. When the sum if 0, the while condition fails and the loop terminates.

An alternative using map was 4 bytes longer:

from random import*
while sum(map(randrange,[6]*n))-2.5*n:print n;n+=2

I've found a bunch of equal-length expressions for a die shifted to mean zero, but none shorter

  • 11
    \$\begingroup\$ I like this one! Mainly because it is the only one that I understand. \$\endgroup\$ – zoecarver Jun 13 '17 at 3:30

MATL, 13 bytes


Try it online!


`       % Do...while top of the stack is truthy
  @E    %   Push 2*k, where k is the iteration index starting at 1
  6     %   Push 6
  y     %   Duplicate 2*k onto the top of the stack
  &Yr   %   Array of 2*k integers distributed uniformly in {1, 2, ..., 6}
  s     %   Sum
  @7*   %   Push 7*k
  -     %   Subtract
        % End (implicit). If the top of the stack is non-zero, the loop
        % proceeds with the next iteration. Else the loop is exited.
        % Display stack (implicit)

Jelly,  19  14 bytes

-5 bytes with help from Leaky Nun (moving from count up to recursion)


A full program printing the results separated by newlines (an extra space and newline are also printed, and the program errors at the end).

Try it online! - any time 6 dice are surpassed TIO kills this due to memory usage, but it works in principle - it also takes ~40s to do so.

A more friendly 15 byte version that does not take so long or require so much memory is available here.


Recursively rolls 2 more dice until the sum of the faces each reduced by 3.5 is zero, printing the number of dice as it goes, when the zero is reached it attempts to use a space character causing a type error.

‘‘6ṗX_3.L⁶S?Ṅß - Main link: no arguments (implicit left=zero)
‘              - increment (initial zero or the previous result)
 ‘             - increment  (= # of dice to roll, n)
  6            - literal 6
   ṗ           - Cartesian power - all possible rolls of n 6-sided dice with faces 1-6
    X          - pick one of them
      3.       - literal 3.5
     _         - subtract 3.5 from each of the roll results
           ?   - if:
          S    -          sum the adjusted roll results (will be 0 for most common)
        L      - ...then: length (number of dice that were rolled)
         ⁶     - ...else: literal ' ' (causes error when incremented in next step)
            Ṅ  - print that plus a newline
             ß - call this link with the same arity (as a monad with the result)
  • \$\begingroup\$ Wow, that is very few bytes. Well done! I am holding off on accepting it until a few more people answer. \$\endgroup\$ – zoecarver Jun 13 '17 at 3:10
  • \$\begingroup\$ Yeah it is normal to wait quite a while before accepting, even if ever doing so. Many people give it a week or two. \$\endgroup\$ – Jonathan Allan Jun 13 '17 at 3:11
  • \$\begingroup\$ also, you are supposed to output all of the iterations - not just the last one. \$\endgroup\$ – zoecarver Jun 13 '17 at 3:14
  • \$\begingroup\$ Oh, I answered an old edit - that completely changes it, I cant use this method in many many ways. \$\endgroup\$ – Jonathan Allan Jun 13 '17 at 3:21
  • \$\begingroup\$ Oh wait just the ns, OK maybe it's salvageable. I thought you meant the sums :) \$\endgroup\$ – Jonathan Allan Jun 13 '17 at 3:22

TI-BASIC, 28 bytes

While mean(randInt(1,6,N)-3.5
Disp N


  • randInt(1,6,N) generates a list of N random numbers from 1 to 6
  • mean(randInt(1,6,N)-3.5 gets the average of the rolls shifted down by 3.5
  • While continues until the average expression equals zero (the most probable sum)

R, 49 bytes


sample(6,n,T) generates n (pseudo)random samples from the range 1:6 with replacement. Subtracting 3.5 from each element yields a result whose sum is 0 (falsey) if and only if it's the most common value.

Try it online!

Skips the odd dice rolls.

  • \$\begingroup\$ This seems to output 80 every time for me, possible bug? \$\endgroup\$ – zoecarver Jun 13 '17 at 3:13
  • \$\begingroup\$ @pudility you can add spaces at the end to try it again; it's caching the inputs/code snippet each time \$\endgroup\$ – Giuseppe Jun 13 '17 at 3:14
  • 3
    \$\begingroup\$ @Giuseppe You can disable the cache in TIO under Settings. \$\endgroup\$ – xnor Jun 13 '17 at 3:20
  • \$\begingroup\$ after I disabled the cache like @xnor said, It worked very well. Thanks for the answer! \$\endgroup\$ – zoecarver Jun 13 '17 at 3:28
  • \$\begingroup\$ @xnor who knew! Good to know in the future. \$\endgroup\$ – Giuseppe Jun 13 '17 at 3:49

Java 8, 123 149 113 108 bytes

()->{for(int n=0,s=1,i;s!=n*7;){for(i=s=++n*2;i-->0;s+=Math.random()*6);if(s!=n*7)System.out.println(n*2);}}

Or 107 bytes if we use an Object null as unused parameter instead.

+26 bytes for a bug-fix, correctly pointed out by @Jules in the comments.
-41 bytes thanks to @OliverGrégoire's great thinking!


Try it here.

()->{                           // Method without parameter nor return-type
  for(int n=0,                  //  Amount of dice
          s=1,                  //  Sum
          i;                    //  Index
      s!=n*7;){                 //  Loop (1) as long as the sum doesn't equal `n`*7,
                                //  because we roll the dice per two, and 3.5*2=7
    for(i=s=++n*2;              //   Reset both the index and sum to `n`*2,
                                //   so we can use random 0-5, instead of 1-6
                                //   and we won't have to use `+1` at `Math.random()*6`
        i-->0;                  //   Inner loop (2) over the amount of dice
        s+=Math.random()*6      //    And increase the sum with their random results
    );                          //   End of inner loop (2)
    if(s!=n*7)                  //   If the sum doesn't equal `n`*7
      System.out.println(n*2);  //    Print the amount of dice for this iteration 
  }                             //  End of loop (1)
}                               // End of method
  • 1
    \$\begingroup\$ I think there is an error in the function. If r equals 3.5*n the program should terminate directly. But, if I understand the function correctly, it would print n one last time before terminating. \$\endgroup\$ – raznagul Jun 13 '17 at 14:48
  • \$\begingroup\$ @raznagul Actually, it wasn't printing an additional time. It was however bugged. What it did before: random 1-12 (bug 1: should have been 2-12); check if this equals 7: if it is: we're done without printing; if it is not: roll 2 dice again (bug 2, should have been 4 dice instead of 2 again); then print 2, and raise n by 2. So it did contain two bugs (1-12 instead of 2-12; and rolling dice like 2 -> 2 -> 4 -> 6 -> ..., instead of 2 -> 4 -> 6 -> ...). It was printing correctly however, because it wouldn't have gone to System.out.println(n),n+=2 if r was indeed equal to 3.5*n. \$\endgroup\$ – Kevin Cruijssen Jun 13 '17 at 17:07
  • 2
    \$\begingroup\$ "Roll two dice at once, by picking a random number from 2-12" -- this is not probabilistically equivalent to rolling two dice and adding the numbers as required in the question, therefore is not a correct solution. \$\endgroup\$ – Jules Jun 13 '17 at 18:41
  • 1
    \$\begingroup\$ Shorter by a few bytes (113), but probably still golfable: ()->{for(int n=2,s=0,e=7,i;s!=e;n+=2,e+=7){for(i=n,s=n;i-->0;)s+=Math.random()*6;if(s!=e)System.out.println(n);}}. Also, correct in regards to Jules' comment and my explanation. n is dices, s is sum, e is expected, i is index. Finally, the sum starts with n to avoid a +1, n times, and s!=e is repeated because I just don't know how to avoid that case. \$\endgroup\$ – Olivier Grégoire Jun 14 '17 at 9:27
  • 1
    \$\begingroup\$ I golfed it a bit again ;) ()->{for(int i=0,s=1,j;s!=i*7;){for(j=s=++i*2;j-->0;)s+=Math.random()*6;if(s!=i*7)System.out.println(i*2);}} \$\endgroup\$ – Olivier Grégoire Jun 14 '17 at 17:50

05AB1E, 22 20 bytes

-2 Bytes thanks to Emigna


Try it online!


[                    # Infinite loop start
 YF     }            # Y times... (Y defaults to 2)
   6L.R               # Push a random number between 1 and 6 (why does this have to be so looooong ._.)
       O              # Sum
         7Y*;ï       # Push 3.5 * Y as an int
              Q      # Is it equal to 3.5 * Y?
               #     # If so: Quit
                Y    # Push Y
                 =   # Print without popping
                  ÌV # Set Y to Y + 2
  • 1
    \$\begingroup\$ If you move O after .R you can remove ) and s. \$\endgroup\$ – Emigna Jun 13 '17 at 11:17

R, 48 44 42 bytes

A 5-byte improvement on Giuseppe's answer.


This (ab)uses the fact that F is a variable by default assigned to FALSE which coerces to 0 and can then be incremented, saving us the need to initialize a counter variable.

  • 1
    \$\begingroup\$ of course, you can save two bytes by calling sample(6) instead of sample(1:6) but crossed out 44 is still 44.... codegolf.stackexchange.com/a/82343/67312 \$\endgroup\$ – Giuseppe Jun 13 '17 at 13:07
  • \$\begingroup\$ @Giuseppe Of course, thanks! I've edited the answer now. \$\endgroup\$ – rturnbull Jun 14 '17 at 8:28

PHP, 75 bytes


Try it online!

  • 1
    \$\begingroup\$ 5^2/++$i*$d+=rand()%6 is a slightly shorter condition for the loop. Also I think the current loop incorrectly exits if the very first "dice" rolled is a "1" (it generates a 0 for the initial $d). \$\endgroup\$ – user59178 Jun 13 '17 at 13:45
  • \$\begingroup\$ @user59178 Nice Idea but it could be make a division by zero error so I must modified it. You are right my solution before stops in this case which is wrong. \$\endgroup\$ – Jörg Hülsermann Jun 13 '17 at 14:25
  • \$\begingroup\$ Your 45-byte answer is invalid because the resulting distribution is not the same as in the question, see here. Your 42-byte answer is, I think, also using the wrong distribution; it seems to assume for example that for two dice, it is equally likely to have 2 and 7 as the sum. \$\endgroup\$ – user34409 Jun 13 '17 at 18:37
  • \$\begingroup\$ @Pakk Yes the 45 Byte answer is invalid. I think your thinking is false what happens at the 42 Byte Version. Look at am expanded version Try it online! \$\endgroup\$ – Jörg Hülsermann Jun 13 '17 at 19:43
  • \$\begingroup\$ @JörgHülsermann That expanded version confirms what I say. In a proper implementation, the value of $r/$i should become closer to 3.5 for bigger values of $i, but I don't see that happening at all. I got an average of 1.16 for 9984 dice, that is statistically extremely unlikely. \$\endgroup\$ – user34409 Jun 13 '17 at 19:55

GolfScript, 41 bytes


Try it online!


Mathematica, 47 bytes


-5 bytes from LLlAMnYP


05AB1E, 17 bytes


Try it online!


[                   # loop over N in 0...
 N·Ì                # push N*2+2
    D               # duplicate
     6L             # push range [1 ... 6]
       ã            # cartesian product (combinations of N*2+2 elements in range)
        .R          # pick one at random
          7;-       # subtract 3.5 from each dice roll
             O_#    # if sum == 0 exit loop
                ,   # otherwise print the copy of N*2+2

Batch, 109 bytes

@for /l %%i in (1,1,%n%)do @call set/as-=%%random%%%%%%6
@if %s% neq 0 echo %n%&%0 %n%

Rather annoyingly, random is a magic environment variable, so it only gets replaced with a random value during environment expansion, which normally happens before the for loop starts. call makes it happen each time through the loop, but then you need to double the % signs to prevent the expansion from happening before the loop. The fun starts because we want to modulo the result by 6, which requires a real % sign, which now has to be doubled twice. The result is six consecutive %s.


JavaScript (ES2015), 75 78 bytes


Outputs a string of results separated by newlines

Edit: saved a byte thanks to Shaggy, added 4 bytes to start function at 2


  [...Array(n)]                // Array of size n
    .reduce(                   // Combine each item
      a=>a+Math.random()*6|0,  // Add a random roll between 0 and 5 for each item
    n)                         // Start at n to correct rolls to between 1 and 6
    ==3.5*n                    // Compare total to most probable roll total
  ? ''                         // If true, end
  : n+'\n'+f(n+2)              // Otherwise, output n and continue


let roll = _ => document.getElementById('rolls').innerHTML = f();
document.getElementById('roll-button').onclick = roll;
<button id="roll-button">Roll</button>
<pre id="rolls"></pre>

  • 2
    \$\begingroup\$ Save a bytes by using a literal newline enclosed in backticks, instead of '\n'. \$\endgroup\$ – Shaggy Jun 13 '17 at 9:23
  • \$\begingroup\$ This does not start with n=2, instead you have to specify the starting number of dice when the function is called. \$\endgroup\$ – MT0 Jun 13 '17 at 12:17

php - 89 Characters

$r=0;$n=2;while($r!=$n*3.5){$r=$i=0;while($i<$n){$r+=rand(1,6);$i++;}print $n."
  • \$\begingroup\$ you need not the first $r=0; use echo instead of print $n." can be write as "$n and for loops instead of while allows do to something in the after loop or before to save some bytes \$\endgroup\$ – Jörg Hülsermann Jun 13 '17 at 17:33

C (gcc), 84 80 79 77 75 80 78 76 bytes


Try it online!


Haskell 133 132 bytes

import System.Random;import Control.Monad
s k=do n<-replicateM k$randomRIO(1,6);if sum n==7*div k 2 then pure()else do print k;s(k+2)

Credit to @Laikoni for the suggestions in the comments below.

  • \$\begingroup\$ 1.) Imports should be counted in the byte count. 2.) return() can be shortened to pure() and putStrLn$show can be shortened to print. \$\endgroup\$ – Laikoni Jun 13 '17 at 17:48
  • \$\begingroup\$ I will fix it right away. Thanks \$\endgroup\$ – Davide Spataro Jun 13 '17 at 18:53
  • \$\begingroup\$ Some further small things: div k 2 then can be div k 2then and do print k;s(k+2) is print k>>s(k+2). \$\endgroup\$ – Laikoni Jun 13 '17 at 20:24

Octave 55 bytes

while mean(randi(6,n,1))-3.5!=0

Inspired by Andrewarchi's answer. If someone has any pointers to even shorten it, they are welcome.

  • \$\begingroup\$ Wow, TI-BASIC and Octave have surprisingly similar syntaxes \$\endgroup\$ – andrewarchi Jun 15 '17 at 1:29
  • \$\begingroup\$ @andrewarchi Octave (the online version is what I use) is just the basics of the basics when it comes to programming. \$\endgroup\$ – Michthan Jun 15 '17 at 11:11

Pyth, 20 bytes


Try it online!

  • \$\begingroup\$ Welcome to PPCG! \$\endgroup\$ – Martin Ender Jun 14 '17 at 12:49
  • \$\begingroup\$ Thanks! Just finished the Pyth tutorial and figured I might give it a try, although this is probably still improvable. Any suggestions are appreciated. \$\endgroup\$ – qwertz Jun 14 '17 at 13:11

QBIC, 40 bytes


Thispretty much literally does what the challenge asks for; seems the shortest way to get the distribution right.


{          DO infinitely
[1,r|      FOR a=1, a<=r (at start, r == 2), a++
g=g+       Add to g (0 at start)
  _r1,6|   a random number between 1 and 6 incl.
]          NEXT
~g=r*3.5   IF the result of all dice rolls equals the expected value
|_X        THEN quit
\g=0       ELSE, reset the dice total
?r┘        PRINT the number of dice used
r=r+2      and add 2 dice.
           END IF and LOOP are courtiously provided by QBIC at EOF.

Rexx (Regina), 78 bytes

do forever
  do x
  say x

Try it online!


JavaScript (ES6) - 69 Characters




r=n=>                                     # Roll n dice
     n?                                   # If there is a dice left to roll
       r(n-1)                             #   Roll n-1 dice
             +(Math.random()*6|0)         #   Add a random number from 0 .. 5
                                 -2.5     #   Subtract 2.5 so sum of average is 0
                                     :0   # Else total is 0


f=(n=2)=>                                 # Start with n = 2
         r(n)                             # Roll n dice
             ?n+"\n"+f(n+2)               # If non-zero then concatenate n, newline and
                                          #    result for n+2 dice
                           :""            # If zero (average) terminate.

Calc2 0.7, 119 118 111 bytes



using "runtime";
var d = 0;
var r = Random();
for(var n = 2; d != 3.5 * n; Console.WriteLine(n), n += 2)
    d = 0;
    for(var i = 0; i < n; i++)
        d += Math.Int(r.Next(1,7));

I could do without the Math.Int() but unfortunately in 0.7 the Random().Next() functions have a bug where they all return doubles instead of ints. It has been fixed but only after this question was posted. I'm not gonna win anything, but hey, nice proof of concept.


  • removed unnecessary space between using and "runtime" (-1 byte)


  • removed var r and create a new Random where it's needed (-4 byte)

  • changed i=0,d=0 to i=d=0 (-2 byte)

  • incremented i after check (-1 byte)


Ruby, 52 bytes

s=x=2;(s=0;p x.times{s+=rand(6)-2.5};x+=2)while s!=0


s=x=2;                                                # sum=2, x=2
      (                                  )while s!=0  # while sum != 0:
       s=0;                                           #  reset the sum
           p                                          #  print
             x.times{              };                 #  repeat x times:
                     s+=                              #   Add to sum:
                        rand(6)                       #    random int in 0..5
                               -2.5                   #    subtract average
                                                      #  (implicitly return x for printing)
                                     x+=2             #  Increment x by 2

Try it online!

  • \$\begingroup\$ @Pakk note the s=0 at the front of the loop and the use of x.times. This means the sum is reset every time and then x dice are rolled, which should be the correct distribution. I'll write up an explanation of my code. \$\endgroup\$ – Value Ink Jun 13 '17 at 19:23
  • \$\begingroup\$ You are correct, I was too fast with my conclusion. \$\endgroup\$ – user34409 Jun 13 '17 at 19:51

Javascript, 87 chars


Test with console.log instead of alert:



lua, 102 bytes

function r(n,t) for d=1,n do t=t+math.random(1,6)end return t==n*3.5 or print(n)or r(n+2,0)end r(2,0)

Or the more readable version

function r(n,t) --recursive function does its magic, t is given to safe usage bytes(no local)
    for d=1,n do --roll n dice and count them up to the total (t)
         t =t+math.random(1,6)
    return t==n*3.5 or --check if t==n*3.5. If it is then it ends
           print(n) or --t != n*3.5 thus print n. print returns nil
           r(n+2,0) --both the check and the return value from print are false thus r gets executed.
r(2,0) --start the process

A more cheaty version for 96 bytes

function r(n,t,m)t=t+m(1,6)+m(1,6)return t==n*3.5 or print(n)or r(n+2,t,m)end r(2,0,math.random)

This pretty much works the same as the first but reuses the rolls from earlier calls. Because of this I can remove the for loop. Both are tested in lua 5.2


Perl 6, 48 bytes

.say for 2,*+2...^{3.5*$_==sum (1..6).pick xx$_}

PHP, 51 bytes

$r=2;$n=2;while(rand(0,6)-2.5*$r){print $n;$n=$n+2;}
  • \$\begingroup\$ If your output is always 2, then this is not a valid answer... \$\endgroup\$ – user34409 Jun 13 '17 at 10:16
  • \$\begingroup\$ If we print $n inside while loop, then it will print the following : 2,4,6,8,10..... \$\endgroup\$ – Shiva Jun 13 '17 at 10:28
  • 2
    \$\begingroup\$ Still, I don't see how this follows the requirements in the question. You use two variables: "$n" and "n". "n" is undefined, so will be set to zero. So effectively, what you do is print an even number, and have a chance of 5/6 of printing the next even number. This is mathematically not equivalent to the distribution in the question. \$\endgroup\$ – user34409 Jun 13 '17 at 11:26
  • \$\begingroup\$ Typo, that n should be always 2, updated the code. \$\endgroup\$ – Shiva Jun 13 '17 at 12:47
  • \$\begingroup\$ Still not what the question asks... Now you are throwing a die, check if it is five (=2*2.5); if the die is five, you stop, and if it is not five, you write the next even number and continue. Mathematically effectively the same as what you did in the previous version of the code. \$\endgroup\$ – user34409 Jun 13 '17 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.