I want to use the uniform_int_distribution in the c++ random library. However, it only does the sampling with replacement, as in the example below. How can I sample without replacement?
#include <iostream>
#include <random>
int main()
{
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(1,4);
for(int i=0; i<4; ++i)
std::cout << distribution(generator) << std::endl;
return 0;
}
Use
std::shuffle
on, say, astd::array<int>
or astd::vector<int>
, initialised to{1, 2, 3, 4}
.Then read back the container contents in order.
This will have better statistical properties than drawing a random number and accepting it only if it hasn't been drawn before.
Reference http://en.cppreference.com/w/cpp/algorithm/random_shuffle