← Patterns

Roll a die

12345678910#include <random> int main() { std::random_device random_device; std::mt19937 random_engine{random_device()}; std::uniform_int_distribution<int> die_distribution{1, 6}; int die_roll = die_distribution(random_engine); }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Generate a random integer according to a uniform distribution.

Description

The std::random_device on line 5 provides a source of uniform non-deterministic random numbers (where such a source is available). We use this to seed the Mersenne Twister random number engine, std::mt19937, on line 6. Consider other random number engines for different properties.

On line 7, we create a std::uniform_int_distribution representing a uniform random distribution of integers from 1 to 6 inclusive. That is, each value from 1 to 6 has an equal chance of occurring.

Finally, we generate a random number from the random engine, distributed according to the uniform integer distribution (line 9). This gives us a random integer from 1 to 6, as though we had rolled a 6-sided die.

To generate further random numbers, simply call die_distribution(random_engine) again.

Contributors

  • Joseph Mansfield

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share