dice

Get a random index into a list of weights corresponding to each index

Similar to rolling a die with relative probabilities stored in proportions. Returns the index in proportions that was chosen.

Note: Usually, dice are 'fair', meaning that each side has equal probability to come up, in which case 1 + uniform(0, 6) can simply be used. In future Phobos versions, this function might get renamed to something like weightedChoice to avoid confusion.

Parameters

rnd Rng

(optional) random number generator to use; if not specified, defaults to rndGen

proportions Num[]

forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value

Return Value

Type: size_t

Random variate drawn from the index values [0, ... proportions.length - 1], with the probability of getting an individual index value i being proportional to proportions[i].

Examples

auto d6  = 1 + dice(1, 1, 1, 1, 1, 1); // fair dice roll
auto d6b = 1 + dice(2, 1, 1, 1, 1, 1); // double the chance to roll '1'

auto x = dice(0.5, 0.5);   // x is 0 or 1 in equal proportions
auto y = dice(50, 50);     // y is 0 or 1 in equal proportions
auto z = dice(70, 20, 10); // z is 0 70% of the time, 1 20% of the time,
                           // and 2 10% of the time
auto rnd = MinstdRand0(42);
auto z = rnd.dice(70, 20, 10);
assert(z == 0);
z = rnd.dice(30, 20, 40, 10);
assert(z == 2);

Meta