View source code Display the source code in std/random.d from which this page was generated on github. 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. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.random.dice

Rolls a dice with relative probabilities stored in proportions. Returns the index in proportions that was chosen.

Prototypes

size_t dice(Rng, Num)(
  Rng rnd,
  Num[] proportions
)
if (isNumeric!Num && isForwardRange!Rng);

size_t dice(R, Range)(
  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);

size_t dice(Num)(
  Num[] proportions
)
if (isNumeric!Num);

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

Authors

Andrei Alexandrescu Masahiro Nakagawa (Xorshift random generator) Joseph Rushton Wakeling (Algorithm D for random sampling)

License

Boost License 1.0.

Comments