std::mt19937 mersenne twister distribution with non repeating values

c++, random

Solution

There's algorithms for that:

// fill a vector ith [0..255]:
std::vector<int> vNumbers(256);
std::iota(vNumbers.begin(), vNumbers.end(), 0);

// shuffle it
std::random_shuffle(vNumbers.begin(), vNumbers.end());

// done

With C++11 you can pass in your own generator for the RNG: (see also comments)

std::shuffle(vNumbers.begin(), vNumbers.end(), twister);

Or you could roll your own (google Fisher-Yates, or see Knuth)

Of course the `iota` can be replaced by te following

for (int i=0; i<256; ++i) vNumbers[i] = i;

Problem

I'd like to use the std::mt19937 random number generator to produce a list of numbers between 0 and 255. "Once a number has been chosen, it should not appear again in the set." - it's this bit I don't know how to do. The mathematical term for this escapes me(!) ``` std::mt19937 twister; std::uniform_int_distribution<int> distribution; twister.seed(91210); distribution = std::uniform_int_distribution<int>(0,255); std::vector vNumbers; vNumbers.resize(256); for( int n = 0; n < 256; ++ n ) vNumbers[n] = distribution(twister); ```

Original source