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 …
2y ago
[Ruby], 28 bytes -> …
1y ago
[Python 3], 59 bytes …
1y ago
[C (gcc)], 48 43 bytes …
1y ago
Japt `-mx`, 3 bytes Takes ` …
2y ago
Vyxal `ṪR`, 3 bytes ``` (⁰ …
2y ago
[Jelly], 4 bytes X}€S …
2y ago
J, 10 7 bytes ```J +/>:?#/ …
12mo ago
Ruby, 27 24 bytes ->n,m{ …
1y ago
9 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
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
Vyxal ṪR
, 3 bytes
(⁰℅
( # N times...
℅ # Generate a random integer between one and...
⁰ # First argument
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
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
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