Calculating odds distribution with 6-sided dice
Posted
by Stephen
on Stack Overflow
See other posts from Stack Overflow
or by Stephen
Published on 2010-04-21T16:29:51Z
Indexed on
2010/04/21
16:33 UTC
Read the original article
Hit count: 431
I'm trying to calculate the odds distribution of a changing number of 6-sided die rolls. For example, 3d6 ranges from 3 to 18 as follows:
3:1, 4:3, 5:6, 6:10, 7:15, 8:21, 9:25, 10:27, 11:27, 12:25, 13:21, 14:15, 15:10, 16:6, 17:3, 18:1
I wrote this php program to calculate it:
function distributionCalc($numberDice,$sides=6) {
for ( $i=0; $i<pow($sides,$numberDice); $i++)
{
$sum=0;
for ($j=0; $j<$numberDice; $j++)
{ $sum+=(1+(floor($i/pow($sides,$j))) % $sides); }
$distribution[$sum]++;
}
return $distribution;
}
The inner $j for-loop uses the magic of the floor and modulus functions to create a base-6 counting sequence with the number of digits being the number of dice, so 3d6 would count as:
111,112,113,114,115,116,121,122,123,124,125,126,131,etc.
The function takes the sum of each, so it would read as: 3,4,5,6,7,8,4,5,6,7,8,9,5,etc. It plows through all 3^6 possible results and adds 1 to the corresponding slot in the $distribution array between 3 and 18. Pretty straightforward. However, it only works until about 8d6, afterward i get server time-outs because it's now doing billions of calculations.
But I don't think it's necessary because die probability follows a sweet bell-curve distribution. I'm wondering if there's a way to skip the number crunching and go straight to the curve itself. Is there a way to do this, so, for example, with 80d6 (80-480)? Can the distribution be projected without doing 6^80 calculations?
I'm not a professional coder and probability is still new to me, so thanks for all the help!
Stephen
© Stack Overflow or respective owner