[OT] Generating distribution of N dice rolls

Ali Çehreli acehreli at yahoo.com
Thu Nov 10 17:46:59 UTC 2022


On 11/10/22 08:57, H. S. Teoh wrote:

 > if there's a fast way to
 > compute the standard deviation of the multinomial

I am happy with my solution which includes scientific terms like 
normalDistributianness. :p

import std;

uint[k] diceDistrib(uint k)(uint N)
in(k > 0)
in(N > 0)
out(r; r[].sum == N)
{
     uint[k] result;
     const average = N / k;

     // foreach (i; 0 .. N) {
     //     result[uniform(0, k)]++;
     // }

     // Larger this value, closer the results to normal distribution
     enum normalDistributianness = 1000;

     // Window around the average of values to pick randomly within
     const halfWindow = average / 2;

     foreach (ref r; result) {
         r = iota(normalDistributianness)
             .map!(_ => uniform(average - halfWindow,
                                average + halfWindow + 1))
             .mean
             .to!uint;
     }

     uint total = result[].sum;

     while (true) {
         if (total == N) {
             break;
         }

         auto which = &result[uniform(0, k)];

         if (total < N) {
             ++(*which);
             ++total;

         } else if (total > N) {
             --(*which);
             --total;
         }
     }

     return result;
}

void main() {
     writeln(diceDistrib!6(100_000_000));
}

Error checking etc. are missing but hundred million dice throws in a 
split second... Now that's fast! :p

Ali



More information about the Digitalmars-d mailing list