I'm having a heck of a time with C++11's <random>. First I tried seeding with random_device and that worked on Mac/Clang and Windows/Visual Studio, but it's broke on GCC (both Windows and Linux) because it returns the same deterministic series of numbers.
From there I've been playing with the Mersenne Twister mt19937_64 and seeding it with chrono::system_clock::now, it appears to be working perfectly fine on my Mac. However, when I tried it on Windows/GCC/DevC++ it spits out the same number multiple times.
I could probably just use the C rand function, but I'd much rather use the C++ implementation so that I can learn more about it... this is an educational exercise at this point.
This is sample the output I get on Windows 10/GCC/DevC++:
46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 46 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 72 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 25 58
This is sample output I get on Mac 10.11.6/Clang/Xcode8:
86 37 83 81 1 84 45 90 16 53 49 57 31 90 79 11 76 87 24 74 89 64 97 90 54 61 62 92 95 29 91 87 7 71 85 1 25 4 59 46 12 21 75 7 9 4 61 38 94 14 71 81 13 100 87 97 32 4 62 82 16 56 83 19 45 19 38 82 28 36 63 14 32 53 83 8 22 9 10 91 41 32 50 1 33 21 37 70 98 77 14 99 11 62 65 38 57 14 76 15
Here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
#include <chrono>
#include <random>
#include <iomanip>
using namespace std;
template <typename T>
inline T get_random_integer (T min, T max) {
mt19937_64 generator ((chrono::system_clock::now().time_since_epoch().count()));
uniform_int_distribution<T> distribution(min, max);
return distribution(generator);
}
int main(int argc, const char * argv[]) {
for (int i; i < 100; i++) {
cout << get_random_integer<int>(0, 100) << " ";
}
return 0;
}
|