View source code
Display the source code in std/random.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.random.dice

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

{null} dice(Rng, Num)()
if (isNumeric!Num && isForwardRange!Rng);

size_t dice(R, Range) (
  ref R rnd,
  Range proportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);

size_t dice(Range) (
  Range proportions
)
if (isForwardRange!Range && isNumeric!(ElementType!Range) && !isArray!Range);

{null} dice(Num)()
if (isNumeric!Num);

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

NameDescription
rnd (optional) random number generator to use; if not specified, defaults to rndGen
proportions forward range or list of individual values whose elements correspond to the probabilities with which to choose the corresponding index value

Returns

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].

Example

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

Example

auto rnd = MinstdRand0(42);
auto z = rnd.dice(70, 20, 10);
writeln(z); // 0
z = rnd.dice(30, 20, 40, 10);
writeln(z); // 2

Example

auto rnd = Xorshift(123_456_789);
auto i = dice(rnd, 0.0, 100.0);
writeln(i); // 1
i = dice(rnd, 100.0, 0.0);
writeln(i); // 0

i = dice(100U, 0U);
writeln(i); // 0

Authors

Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling) Ilya Yaroshenko (Mersenne Twister implementation, adapted from mir-random)

License

Boost License 1.0.