Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there some function, similar to srand(), that I need to call to make sure that std::random_shuffle() always produces different results? i.e. if I call it several times with the same data, I want the order to be different every time. How can I make sure of that?

like image 589
laurent Avatar asked Aug 03 '11 19:08

laurent


6 Answers

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.

like image 109
Dave S Avatar answered Nov 19 '22 05:11

Dave S


std::random_shuffle has a template overload for specifying the RNG.

template <class RandomAccessIterator, class RandomNumberGenerator>
  void random_shuffle ( RandomAccessIterator first, RandomAccessIterator last,
                        RandomNumberGenerator& rand );

reference

like image 32
Tom Kerr Avatar answered Nov 19 '22 05:11

Tom Kerr


random_shuffle is deprecated since C++14 (removed in C++17) and replaced with shuffle (exists since C++11) http://en.cppreference.com/w/cpp/algorithm/random_shuffle

possible usage:

shuffle(items.begin(), items.end(), std::default_random_engine(std::random_device()()));
like image 5
sluki Avatar answered Nov 19 '22 03:11

sluki


I think you can give a random generator functor to std::random_shuffle, so you can be able to fully control the random number generation. Looking here, this functor takes the place of the RandomNumberGenerator template argument.

like image 3
neodelphi Avatar answered Nov 19 '22 05:11

neodelphi


Generally call srand(time(NULL)) before calling std::random_shuffle() would give you what you need, it give you different result each time you call std::random_shuffle(). It's because std::random_shuffle() internally calls rand() in many popular implementations (e.g. VS-2008 and GCC).

Of course you can supple a RNG yourself if you want to call the other overloaded std::random_shuffle with a extra parameter.

like image 3
RoundPi Avatar answered Nov 19 '22 03:11

RoundPi


As a last resort, you can:

  • Call std::random_shuffle
  • Compute a hash of the sequence, store it in a std::set
  • Discard if the hash is already present

I fail to see how using a custom generator could guarantee that the sequence is unique.

like image 2
Alexandre C. Avatar answered Nov 19 '22 05:11

Alexandre C.