Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross Platform Random Reproducibility

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?

like image 785
scanner Avatar asked Aug 20 '18 10:08

scanner


1 Answers

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.

like image 94
Passer By Avatar answered Nov 05 '22 01:11

Passer By