I need to use a random function, but also have it repeating on different devices (PC / iOS / Android). I'm running this sample code, to shuffle a vector:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
#include <vector>
int main() {
std::mt19937 generator(1337);
std::cout << "Your seed produced: " << generator() << std::endl;
std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::shuffle(v.begin(), v.end(), generator);
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
return 0;
}
Output from two different PCs (windows):
Your seed produced: 1125387415
10 6 8 1 7 2 4 3 5 9
Output from iOS:
Your seed produced: 1125387415
9 1 4 6 7 8 5 3 10 2
Why am I getting different results? Is there another dependency relating to the OS itself? How is it possible to get this to work cross-platform?
std::mt19937
is rigorously defined by the standard and has no room for platform specific/implementation defined behaviour, your problem doesn't lie here.
The problem is with std::shuffle
, which in no way says how it is supposed to use the random number generator, just that is has to use it.
Which unfortunately means, if you want a reproducible shuffling behaviour, you might need to implement your own.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With