I have a short piece of code which runs the Mersenne Twister PRNG and it works great:
std::random_device randDev;
std::mt19937 twister(randDev());
std::uniform_int_distribution<int> dist(0,99);
for (int i = 0; i < 10; i++) {
std::cout << dist(twister) << std::endl;
}
It outputs ten random numbers. However if I put the exact same code into a function:
#include <random>
int getRand(const int& A, const int& B) {
std::random_device randDev;
std::mt19937 twister(randDev());
std::uniform_int_distribution<int> dist(A,B);
return dist(twister);
}
int main() {
for (int i = 0; i < 10; i++) {
std::cout << getRand(0,99) << std::endl;
}
return 0;
}
It outputs the same number ten times. I'm just starting out with C++ so I have no idea what causes this or how to go about fixing the problem.
EDIT: The problem lies with std::random_device. It could be a bug in Eclipse C++ IDE (Luna version) or MinGW 4.8.1 but for whatever reason that random number is always the same. I believe time(0) will be a suitable seed for my uses.
EDIT 2: Taking T.C.'s suggestion into account and the fact that time(0) still results in ten of the same number, here's the final code so far. I know rand() is bad but it works.
#include <iostream>
#include <random>
std::mt19937 twister(rand());
int getRand(const int& A, const int& B) {
std::uniform_int_distribution<int> dist(A,B);
return dist(twister);
}
int main() {
for (int i = 0; i < 10; i++) {
std::cout << getRand(0,99) << std::endl;
}
return 0;
}