How to Make Sure That Std::Random_Shuffle Always Produces a Different Result

How to make sure that std::random_shuffle always produces a different result?

std::random_shuffle has two forms. One that takes 2 arguments (begin/end iterators), and one that takes 3 (begin/end iterator and a random generator).

The first form uses std::rand(), so you would use std::srand() to seed it's random number generator. You can also use the 3-argument version and provide the RNG yourself.

std::random_shuffle produces same result each time

C++ random numbers aren't truly random - they are generated from initial value called seed. If you don't set the seed, it will always be the same, so generated sequence won't change. std::random_shuffle depends on random number generation, so it will behave this way as well.

So how to set the seed? Use:

srand(time(0));

before any calls to functions using random numbers. It will set the seed to current time in seconds. Don't forget to add appropritate header files.

std::random_shuffle produce the same result even though srand(time(0)) called once

random_shuffle() isn't actually specified to use rand() and so srand() may not have any impact. If you want to be sure, you should use one of the C++11 forms, random_shuffle(b, e, RNG) or shuffle(b, e, uRNG).

An alternative would be to use random_shuffle(indices.begin(), indices.end(), rand()); because apparently your implementation of random_shuffle() is not using rand().

Vector of multiple classes do not shuffle as expected using random_shuffle

In order for std::random_shuffle to return different values at different runs, it needs to be given a non-fixed seed.

You can solve this by adding the line:

std::srand(std::time(NULL));

Now executions at least 1 second apart will give different shuffling results.

random_shuffle algorithm - are identical results produced without random generator function?

25.2.11 just says that the elements are shuffled with uniform distribution. It makes no guarantees as to which RNG is used behind the scenes (unless you pass one in) so you can't rely on any such behavior.

In order to guarantee the same shuffle outcome you'll need to provide your own RNG that provides those guarantees, but I suspect even then if you update your standard library the random_shuffle algorithm itself could change effects.

Is std::random_shuffle reproducible across different compilers?

From reading "25.3.12 Random shuffle" in the C++11 standard (the one I have here) I would conclude that strictly spoken that guarantee can not be made. The only requirement for the algorithm is "that each possible permutation of those elements has equal probability of appearance". It does not have to swap the elements front to back, for example, and the iterators are random access iterators so that any other order is possible. (That said, I'd be surprised if an implementation wouldn't go first -> last, but it's not guaranteed.)



Related Topics



Leave a reply



Submit