I want to shuffle an array in C++, and each time the program is run, I want to have a different random shuffling. I have myArray
of length. Currently I am using:
random_shuffle(myArray, myArray+N)
will use std::rand() to obtain random numbers. If you want the random sequence to be different each time the program is run you need to seed the random generator first using std::srand(). It is common to seed the random number generator using the current system time, which is usually good enough for non-security-related purposes. You only need to do this once during your program's execution.
std::srand(std::time(0));
If you do not call std::srand()
before the first time std::rand()
is called, then std::rand()
behaves as though you had called std::srand(1)
-- that is, you implicitly seed it with the same value each time the program is run, which will produce the same random sequence each execution of the program.