Generating a random integer from a range

The simplest (and hence best) C++ (using the 2011 standard) answer is:

#include <random>

std::random_device rd;     // Only used once to initialise (seed) engine
std::mt19937 rng(rd());    // Random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // Guaranteed unbiased

auto random_integer = uni(rng);

There isn’t any need to reinvent the wheel, worry about bias, or worry about using time as the random seed.

Leave a Comment