14
\$\begingroup\$

Suppose you have two six-sided dice. Roll the pair 100 times, calculating the sum of each pair. Print out the number of times each sum occurred. If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled.

Example Output: [3, 3, 9, 11, 15, 15, 11, 15, 7, 8, 3]

The number of times a sum was rolled is represented in the sums index - 2

In this example, a sum of two was rolled 3 times ([2-2]), a sum of three 3 times ([3-2]), a sum of four 9 times ([4-2]), and so on. It does not matter the individual dice rolls to arrive at a sum (5 and 2 would be counted as the same sum as 6 and 1)

"Ugly" outputs are fine (loads of trailing zeros, extra output, strange ways of representing data, etc.) as long as you explain how the data should be read.

\$\endgroup\$
  • 2
    \$\begingroup\$ Do you mean "print out the number of times each pair occurred" or "print out the number of times each sum occurred"? \$\endgroup\$ – Esolanging Fruit May 24 '17 at 5:21
  • 1
    \$\begingroup\$ If a particular sum never comes up, does there need to be a 0 in the list, or can it be omitted? \$\endgroup\$ – Greg Martin May 24 '17 at 5:34
  • 1
    \$\begingroup\$ Do the different values need to be consistently identifiable or do the counts alone suffice? \$\endgroup\$ – Jonathan Allan May 24 '17 at 5:35
  • 1
    \$\begingroup\$ If the output is just the number of times each combination of pairs occurs, why do we need to sum the value of each roll? What are we supposed to do with that total? What do you mean by "ugly"? \$\endgroup\$ – Shaggy May 24 '17 at 7:09
  • 1
    \$\begingroup\$ extra output but we still can't output an infinite list of random numbers and say it randomly appears somewhere in there, right? That's a standard loophole iirc. \$\endgroup\$ – Stephen May 24 '17 at 15:59

23 Answers 23

5
\$\begingroup\$

Jelly, 13 12 bytes

³Ḥ6ẋX€+2/ṢŒr

A niladic link. Output format is a list of lists of [value, count].

(Zero rolls means no such entry is present in the output - e.g. an output of[[6, 12], [7, 74], [8, 14]] would identify that only sums of six, seven and eight were rolled.)

Try it online!

How?

³Ḥ6ẋX€+2/ṢŒr - Main link: no arguments
³            - 100
 Ḥ           - double = 200
  6          - 6
   ẋ         - repeat -> [6,6,6...,6], length 200
    X€       - random integer from [1,z] for €ach (where z=6 every time)
       2/    - pairwise reduce with:
      +      -   addition (i.e. add up each two)
         Ṣ   - sort
          Œr - run-length encode (list of [value, length] for each run of equal values)
\$\endgroup\$
4
\$\begingroup\$

Python 2, 84 77 76 bytes

-7 bytes thanks to @JonathanAllan
-1 byte thanks to @FelipeNardiBatista

from random import*
a=[0]*13
exec'a[%s]+=1;'%('+randint(1,6)'*2)*100
print a

Try it online!

The output has two leading zeros

\$\endgroup\$
3
\$\begingroup\$

05AB1E, 21 19 bytes

-2 bytes thanks to @Emigna

TÝÌтF6Lã.RO¸ì}{γ€g<

Try it online!

TÝÌтF6Lã.RO¸ì}{γ€g<
TÝÌ                   Range from 2 to 12
   тF                 100 times do:
     6L                 Range from 1 to 6
       ã                Cartesian product (creates all possible pairs of 1 and 6)
        .RO             Choose random pair and sum
           ¸ì           Prepend result to initial list
             }        end loop
              {γ€g<   Sort, split on consecutive elements, count and decrement
\$\endgroup\$
  • \$\begingroup\$ TÝÌтF6Lã.RO¸ì}{γ€g< saves 2 bytes. \$\endgroup\$ – Emigna Sep 15 '17 at 11:30
  • \$\begingroup\$ @Emigna, didn't expect looping to be shorter, thanks! \$\endgroup\$ – kalsowerus Sep 15 '17 at 12:13
2
\$\begingroup\$

Mathematica, 50 bytes

r:=RandomInteger@5
Last/@Tally@Sort@Table[r+r,100]

Straightforward implementation. If any sum is never achieved, the 0 is omitted from the list.

\$\endgroup\$
2
\$\begingroup\$

MATL, 17 bytes

6H100I$Yrs!11:Q=s

Output is a list of 11 numbers (some of them possibly 0) separated by spaces, indicating the number of times for each pair from 2 to 12.

Try it online!

For comparison, the theoretical average number of times each pair will appear on average can be computed as 6:gtY+36/100*.

If the number of rolls is increased the obtained values approach the theorerical ones. See for example the obtained and theoretical values with 10000 rolls.

\$\endgroup\$
2
\$\begingroup\$

CJam, 18 20 bytes

100{;6mr6mr+))}%$e``

Try it online!

\$\endgroup\$
  • \$\begingroup\$ It outputs in an ugly format - the number of times each roll occurred is represented as the length of the continuous segments. \$\endgroup\$ – Esolanging Fruit May 24 '17 at 5:21
  • \$\begingroup\$ @JonathanAllan All right, fine then. e` only takes two bytes. \$\endgroup\$ – Esolanging Fruit May 24 '17 at 5:25
2
\$\begingroup\$

Perl 6, 30 bytes

bag [Z+] (^6).pick xx 100 xx 2

(^6).pick is a random number from zero through five. xx 100 makes a hundred-element list of such numbers. xx 2 produces two such lists. [Z+] zips those two lists with addition, producing a hundred-element list of two-die rolls. Finally, bag puts that list into a bag, which is a collection with multiplicity. Example REPL output:

bag(1(4), 9(4), 0(4), 4(14), 5(18), 3(9), 10(2), 6(19), 7(13), 2(3), 8(10))

That means 1, 9, and 0 occurred four times each, four occurred fourteen times, etc. Since the "dice" in this code produce a number from 0-5, add two to each of these numbers to get the rolls a pair of standard 1-6 dice would produce.

\$\endgroup\$
  • \$\begingroup\$ Wow. Perl 6 is a force to be reckoned with. \$\endgroup\$ – Jakob Aug 23 '17 at 16:52
  • \$\begingroup\$ However, "If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled." Doesn't look like the bag solution satisfies that. \$\endgroup\$ – Jakob Aug 23 '17 at 16:56
  • \$\begingroup\$ If a particular number was not rolled, that situation can be identified by the number's absence in the bag. \$\endgroup\$ – Sean Aug 23 '17 at 17:23
2
\$\begingroup\$

R, 45 37 bytes

-7 bytes thanks to Jarko Dubbledam

s=sample;table(s(6,100,T)+s(6,100,T))

Returns a table object of elements and counts of each. Excludes any values that didn't occur.

Try it online!

old version:

rle(sort(colSums(matrix(sample(6,200,T),2))))

sample(6,200,T) samples 200 times from 1:6 uniformly with replacement, then it makes a matrix with 2 rows, sums the columns, then sorts them into ascending order and computes the lengths of the runs. Omits any dice sums that aren't attained.

Returns an rle object, which prints by default in the following format:

Run Length Encoding
  lengths: int [1:11] 5 6 8 12 12 20 12 11 4 7 ...
  values : num [1:11] 2 3 4 5 6 7 8 9 10 11 ...

where lengths are the counts and the values are the dice sums.

TIO Link

\$\endgroup\$
1
\$\begingroup\$

PHP, 53 Bytes

prints an associative array. key is result of two dices and value is the count of these results

for(;$i++<100;)$r[rand(1,6)+rand(1,6)]++;print_r($r);

Try it online!

\$\endgroup\$
  • \$\begingroup\$ If a sum was never rolled, you must include a zero or some way to identify that that particular sum was never rolled. \$\endgroup\$ – Titus Aug 23 '17 at 5:29
1
\$\begingroup\$

JavaScript (ES6), 72 bytes

Seeing as "ugly" output is allowed, the following will output an array containing the number of times each score from 2-12 was rolled, with an additional 89 elements set to 0.

_=>(a=Array(100).fill(0)).map(_=>a[g()+g()]++,g=_=>Math.random()*6|0)&&a

f=
_=>(a=Array(100).fill(0)).map(_=>a[g()+g()]++,g=_=>Math.random()*6|0)&&a
o.innerText=f()
<pre id=o>

\$\endgroup\$
  • \$\begingroup\$ Aren't you wasting a byte to make it 100 elements instead of 99 or 20 or just even 12? \$\endgroup\$ – Rohan Jhunjhunwala May 27 '17 at 13:41
  • \$\begingroup\$ @RohanJhunjhunwala, the challenge calls for 100 rolls of the two dice. \$\endgroup\$ – Shaggy May 27 '17 at 18:01
  • \$\begingroup\$ Oh, i thought were just initializing a 100 element array to store the rolls. \$\endgroup\$ – Rohan Jhunjhunwala May 27 '17 at 18:19
1
\$\begingroup\$

S.I.L.O.S, 99 bytes

i=100
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
lblb
c=get b
printInt c
b+1
d=11-b
if d b

Try it online!

Rolls the dice, and stores them in the first 11 spots of the heap, then just iterates through the heap printing each counter. This is one of the first recorded uses of the rand keyword combined with an assignment operator.

It is worth noting, that a few modifications can be made to output a histogram of the rolls. enter image description here

Unfortunately it must be run from the offline interpreter.

i=4000
lbla
x=rand*6+rand*6
a=get x
a+1
set x a
i-1
if i a
canvas 1100 1000 Output
lblb
c=get b
printInt c
d=c*1
y=1000-d
x=b*100
newObj 0 100 d
moveObj b x y
b+1
d=11-b
if d b
wait 10000
\$\endgroup\$
1
\$\begingroup\$

Elixir, 157 118 bytes

l=&Enum.random(1..&1)
p=fn(o,s)->y=l.(6)+l.(6)
s=List.update_at(s,y,&(&1+1))
if Enum.sum(s)<100 do s=o.(o,s) end
s end

Tried something harder than Jelly.

Explanation:

  1. Define function that returns a random number between 1 and 6 inclusive.
  2. Define the function anonymously and let y be the variable with the roll sum.
  3. update the appropriate place in the list by adding 1.
  4. if we are 100 rolls in, quit. Else call yourself again passing in yourself and the updated list.
  5. return the updated array.

Should be called like p.(p,[0,0,0,0,0,0,0,0,0,0,0,0,0]). It will raise a warning, but it will return the desired array with 13 elements, the first 2 should be ignored.

\$\endgroup\$
1
\$\begingroup\$

Java 8, 104 bytes

A lambda returning an int[] of frequencies. Assign to Supplier<int[]>.

()->{int o[]=new int[11],i=0;while(i++<100)o[(int)(Math.random()*6)+(int)(Math.random()*6)]++;return o;}

Try It Online

Ungolfed lambda

() -> {
    int
        o[] = new int[11],
        i = 0
    ;
    while (i++ < 100)
        o[(int) (Math.random() * 6) + (int) (Math.random() * 6)]++;
    return o;
}
\$\endgroup\$
1
\$\begingroup\$

q/kdb+, 31 28 25 bytes

Solution:

sum!:[11]=/:sum(2#100)?'6

Example:

q)sum!:[11]=/:sum(2#100)?'6
1 3 5 11 16 21 16 9 8 9 1i

Explanation:

Roll a dice 100?6 , roll a dice again and add the vectors together. Then see where each results matches the range 0..10, then sum up all the trues in each list:

sum til[11]=/:sum(2#100)?'6 / ungolfed solution
                 (2#100)    / 2 take 100, gives list (100;100)
                        ?'6 / performs rand on each left-each right, so 100 & 6, 100 & 6
              sum           / add the lists together
    til[11]                 / the range 0..10
           =/:              / apply 'equals?' to each right on left list
sum                         / sum up the results, e.g. how many 1s, 2s, 3s.. 12s

Notes:

'Golfing' is mostly swapping out q keywords for the k equivalents, namely each and til.

\$\endgroup\$
0
\$\begingroup\$

QBIC, 45 bytes

[100|h=_r1,6|+_r1,6|-2┘g(h)=g(h)+1][0,z|?g(b)

Explanation:

[100|         FOR a = 1 to 100
h=_r1,6|       set h to a random value between 1-6
 +_r1,6|       + another rnd(1,6) (2, 3 ... 11, 12)
 -2            - 2 (index: 0 ... 10
┘             Syntactic linebreak
g(h)          When using array parenthesis on an undefined array,
              it is interpreted as an array with 10 indexes of all zeroes.           
    =         Of array g, set the value of index h (0 ... 11)
      g(h)+1  to one higher (all indices start out as 0)
              Note that we need to track 11 values. Fortunately, QBasic'set
              empty, 10-sized array has 11 indices, because of base 0 / base 1 ambiguity.
]             NEXT set of dice
[0,z|         FOR b = 0 to 10
?g(b)           PRINT the tracker array
\$\endgroup\$
0
\$\begingroup\$

APL, 14 bytes

,∘≢⌸+/?100 2⍴6

Presents data as a table with the left column representing the sum and the right representing the number of occurrences.

Explained

        100 2⍴6  ⍝ create an 2×100 array of 6
       ?         ⍝ roll for each cell from 1 to 6
     +/          ⍝ sum every row
   ⌸            ⍝ for every unique sum
,∘≢              ⍝ get the sum and the number of indexes

Previous post:

APL, 36 31 bytes

5 bytes saved thanks to @Adám

(11⍴⍉⌽f)[⍋11⍴⍉f←,∘≢⌸+/?100 2⍴6]

Explanation

f←,∘≢⌸+/?100 2⍴6
          100 2⍴6    ⍝ create an 2×100 array of 6
         ?           ⍝ roll for each cell from 1 to 6
       +/            ⍝ sum every row
     ⌸              ⍝ for every unique sum
  ,∘≢                ⍝ get the sum and the number of indexes

(11⍴⍉⌽f)[⍋11⍴⍉f]  ⍝ ⍋x returns the indexes of the sorted x in the current x  
                     ⍝ x[y] find the yth elements of x
                     ⍝ x[⍋y] reorders x the same way that would be required to sort y

            11⍴⍉f   ⍝ the column of sums - see below
 11⍴⍉⌽f            ⍝ the column of counts - see below

How does 11⍴⍉⌽f works?

⍝ ⌽ - Reverses the array
⍝ ⍉ - Transposes the array

  ⍝   f
 9 14   ⍝ Sum - Occurences
 4  9
 7 17
 8 18
 6 15
 5  7
10  3
11  5
 3  6
 2  2
12  4

  ⍝   ⍉f
 9 4  7  8  6 5 10 11 3 2 12  ⍝ Sum
14 9 17 18 15 7  3  5 6 2  4  ⍝ Occurences

  ⍝   ⍉⌽f
14 9 17 18 15 7  3  5 6 2  4  ⍝ Occurences
 9 4  7  8  6 5 10 11 3 2 12  ⍝ Sum
\$\endgroup\$
  • \$\begingroup\$ Save a few bytes by combining the statements and making the operand tacit: (11⍴⍉⌽f)[⍋11⍴⍉f←,∘⍴⌸+/?100 2⍴6] \$\endgroup\$ – Adám May 28 '17 at 18:39
  • \$\begingroup\$ Sorry, I edited my suggestion while you incorporated it. Notice the tacit operand. \$\endgroup\$ – Adám May 28 '17 at 18:44
  • \$\begingroup\$ However, OP allows any unambiguous output format, so ,∘⍴⌸+/?100 2⍴6 should be enough, as it lists the occurring sums (thus indicating which ones are not there) and their frequencies (so no sorting is needed). \$\endgroup\$ – Adám May 28 '17 at 18:45
0
\$\begingroup\$

><>, 93 bytes

00[0[v
v 1\v/4
v 2xxx5
v 3/^\6
>l2(?^+]laa*=?v0[
  /&1+&\ v1&0]<
=?/ :?!\}>:@@:@
oa&0n&}< ^+1

Try it online, or watch it at the fish playground!

The ugly output format is a sequence of numbers separated by newlines, where the nth number says how many times the sum was n — it's ugly because it prints forever, for all positive integers n, although most of the lines will be 0. (The TIO link is modified to stop after n=12, at the cost of 5 bytes.)

The fish playground is fairly slow — it takes about three and a half minutes to print up to n=12 at top speed — so you may want to modify it to roll 10 pairs of dice instead of 100 by changing the aa* in the 5th line to a   (that is, a followed by two spaces).

The random dice rolls are done by this bit:

1\v/4
2xxx5
3/^\6

The xs change the fish's direction randomly. Assuming that's implemented with equal probabilities, it's clear that the die roll result is a uniform distribution by symmetry.

Once the fish has rolled 100 pairs of dice, it counts how many times the sum was n with this bit (unwrapped for clarity, and starting in the top left):

v       /&1+&\
>:@@:@=?/ :?!\}
^   +1oa&0n&}<

We keep n at the front of the stack, and use the register to count the number of times n appears.

\$\endgroup\$
0
\$\begingroup\$

Javascript 85 75 characters

Thanks Shaggy!

a=[]
for(i=100;i--;)a[o=(f=_=>Math.random()*6|0)()+f()]=(a[o‌​]|0)+1
alert(a)

History

85

a={}
f=_=>Math.random()*6
for(i=0;i++<100;)a[o=-~f()-~f()]=(a[o]||0)+1
console.log(a)
\$\endgroup\$
  • \$\begingroup\$ Kept meaning to give you a few savings for this; here's a very quickly golfed 75 byte version of your solution: a=[];for(i=100;i--;)a[o=(f=_=>Math.random()*6|0)()+f()]=(a[o]|0)+1;alert(a). (Note: in this instance, the IIFE neither saves nor costs any bytes but there are times when it can save you a byte or 2, so it's handy to have it in your "golfbag".) \$\endgroup\$ – Shaggy May 30 '17 at 18:00
  • \$\begingroup\$ Oh, awesome, thanks. Useful tricks there! So interesting that |0 is the golfy solution to "Math.floor()" and also to "convert undefined to 0". \$\endgroup\$ – Steve Bennett Jun 1 '17 at 0:12
0
\$\begingroup\$

Perl 5, 64 bytes

map$s{2+int(rand 6)+int rand 6}++,1..100;say"$_ $s{$_}"for 2..12

Try it online!

Output format:

<sum> <# rolls>

For sums with zero rolls, the rolls column is blank.

\$\endgroup\$
0
\$\begingroup\$

PHP, 65 bytes

while($i++<100)${rand(1,6)+rand(1,6)}++;for(;++$k<13;)echo+$$k,_;

prints a leading 0_ and then the occurences of 2 to 12, followed by an underscore each.
Run with -nr or try it online.

\$\endgroup\$
0
\$\begingroup\$

K (oK), 24 22 bytes

Solution:

+/(!11)=/:+/(2#100)?'6

Try it online!

Explanation:

k 'port' of my q solution. Evaluation occurs right-to-left, hence brackets around the til (!)

+/(!11)=/:+/(2#100)?'6 / the solution
            (2#100)    / the list (100;100)
                   ?'6 / take 6 from each left/each right (roll the dice twice)
           +/          / sum rolls together
  (!11)                / til, performs range of 0..n-1, thus 0..10
       =/:             / equals each right (bucket the sum of the rolls)
+/                     / sum up to get counts per result

Edits:

  • -2 bytes switching the each-left for an each-both, and the each-left + flip for each-right
\$\endgroup\$
0
\$\begingroup\$

Pyth, 21 bytes

V100aY,O6O6)VTlfqsTNY

Outputs each step in the creation of the rolls, then outputs frequency of each sum 0 - 10 on a separate line.


V100aY,O6O6)VTlfqsTNY Full program, no input, outputs to stdout
V100                  For N from 0 to 100
    a ,O6O6           Append a pair of random ints below 6
     Y                To a list Y, initialized to the empty list
           )          Then
            VT        For N from 0 to 10
              f     Y Print Y filtered to only include pairs
                q  N  For which N is equal to
                 sT   The sum of the pair
\$\endgroup\$
0
\$\begingroup\$

Java (OpenJDK 8), 95 bytes

a->{int r[]=new int[11],i=0,d=0;for(;i++<200;)r[d+=Math.random()*6]+=i%2<1?1-(d=0):0;return r;}

Try it online!

Explanations

a->{
  int r[] = new int[11],     // Rolls or result
      i   = 0,               // Iteration
      d   = 0;               // Dice accumulator
  for (;i++<200;)
    r[d+=Math.random()*6] += // Accumulate a new die and start an addition
     i % 2 < 1               // Accumulate up to two dice
       ? 1 - (d = 0)         // If we're at 2 dice, reset the accumulator and add 1
       : 0;                  // If we only have one die, add 0
  return r;
}
\$\endgroup\$

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.