lundi 24 juillet 2017

How to shuffle a collection of integers so that the output is same in both C++ and Java?

I am porting a piece of code from C++ to Java. In C++, I shuffle a vector<int> as below:

std::vector<int> integers(10); //Size is not constant and can change.
std::iota(std::begin(std::begin(integers), std::end(integers), 0); //fills the vector with integers from 0 to 9
std::mt19937 gen;
gen.seed(integers.size());
std::shuffle(std::begin(integers), std::end(integers), gen);

After doing some reseach, I found out that, java uses Linear Congruential Generator (LCG) to generate random numbers. In order to use same parameters used by Java.util.random for LCG, I changed my random number generator engine to (According to this wikepedia page LCG):

std::linear_congruential_engine<unsigned long, 0x5DEECE66D, 11, 281474976710655>  engine(10);

C++ shuffled result : 6,9,0,3,8,4,1,2,7,5

Here is the correspoding Java code:

ArrayList<Integer> array = new ArrayList(10);
for(int i = 0; i < 10; ++i){
    array.add(i, i);
}
Collections.shuffle(array,  new Random(10));
for(int i = 0; i < 10; ++i){
    System.out.print(array.get(i));
}

Java shuffled result: 9,7,8,0,1,4,5,2,6,3

  1. Is there a way to make C++ stadard random number generators to behave the same way as of Java or vice versa?
  2. Is there any other (probably simpler) approach I could take to solve this problem? I don't mind changing my existing C++ code.



Aucun commentaire:

Enregistrer un commentaire