I have the following piece of code:
unsigned int randomInt()
{
mt19937 mt_rand(time(0));
return mt_rand();
};
If I call this code, for example 4000 times in a for loop, I don't get random unsigned integers, instead I get for example 1000 times one value and the next 1000 times I get the next value.
What am I doing wrong?
This happens because you call
f4000 times in a loop, which probably takes less than a mili second, so at each calltime(0)returns the same value, hence initializes the pseudo-random generator with the same seed. The correct way is to initialize the seed once and for all, preferably via astd::random_device, like so: