Roll n fair dice
Challenge
This is a simple randomness challenge: Given a non-negative integer $n$, and positive integer $m$, simulate rolling and summing the results of $n$ fair dice, each of which have $m$ sides numbered $1$ through $m$.
Here is a basic ungolfed example in Python:
from random import randint
def roll(n, m):
return sum([randint(1, m) for i in range(n)])
Try it online! (Also includes a basic visualization of the resulting distribution)
This is code golf, so shortest code wins!
[Python 3], 61 bytes …
3y ago
[Ruby], 28 bytes -> …
2y ago
Dyalog APL, 2 bytes ```apl …
1y ago
[Python 3], 59 bytes …
2y ago
[C (gcc)], 48 43 bytes …
2y ago
J, 10 7 bytes ```J +/>:?#/ …
2y ago
Ruby, 27 24 bytes ->n,m{ …
3y ago
Japt `-mx`, 3 bytes Takes ` …
3y ago
Vyxal `ṪR`, 3 bytes ``` (⁰ …
3y ago
[Jelly], 4 bytes X}€S …
3y ago
10 answers
Python 3, 61 bytes
lambda n,m:sum(randint(1,m)for i in[0]*n)
from random import*
This is not an interesting answer as it is just a copy of your code. I tried to do it with choices but it's 1 byte longer : Try it online!
0 comment threads
Dyalog APL, 2 bytes
?⍴
Dyadic 2-train, takes $n$ as its left argument and $m$ as its right argument
The Roll function ?
expects an array of maximum bounds and replaces each item with a random number between 1 and that bound (ie ?2 6 5
returns (random between 1 and 2) (random between 1 and 6) (random between 1 and 5)
. Reshape ⍴
is used to convert $n$ and $m$ to the list $[m, m, \dots(n\text{ times}), m]$.
0 comment threads
Vyxal ṪR
, 3 bytes
(⁰℅
( # N times...
℅ # Generate a random integer between one and...
⁰ # First argument
0 comment threads
Ruby, 27 24 bytes
->n,m{eval'-~rand(m)'*n}
If we change the order of n, m
parameters to m, n
then following 23 bytes version work, but only in ruby 2.7 (it does not work in 3.x - bug or feature?):
->{eval'-~rand(_1)'*_2}
0 comment threads
C (gcc), 48 43 bytes
s;r(n,m){s+=rand()%m+1;return--n?r(n,m):s;}
Previous 48 bytes version using loop:
i,s;r(n,m){for(;i<n;i++)s+=rand()%m+1;return s;}
0 comment threads
Jelly, 4 bytes
X}€S
How it works
X}€S - Main link. Takes n on the left, m on the right
€ - Over each element of 1 through n:
} - With m as its argument:
X - Yield a random integer from 1 to m
S - Sum
0 comment threads
J, 10 7 bytes
+/>:?#/
+/>:?#/
#/ : Inserts dyadic # into an array n m
Creates n copies of m
? : Roll from 0..y
>: : Increment
+/ : Sum reduce
-3 bytes thanks to torres.
0 comment threads