0

In my program, I have a function return_random_vector() which takes a set of numbers, say 1,2,3,4,5, and returns a random rearrangement of the numbers such as 2,5,1,4,3.

In order to do this, I set the seed srand(time(NULL)). For my program, I want to be able to call this function again with 1,2,3,4,5 and get another rearrangement of them, for example 3,1,4,5,2.

Is there a way I can set srand() so that the seed can be reset?

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
potatosoup
  • 45
  • 1
  • 9

3 Answers3

3

To get a different set, you can call return_random_vector() again without calling srand() in between.

Calling srand((unsigned)time(NULL)) right after the first call to return_random_vector() will likely generate the same set because time() will probably return the same value, which is the elapsed time in seconds.

So you would in fact be resetting the seed to the same value as it was before the first call. And setting the seed to the same value will generate the same set of random numbers again.

You could also take a look at std::shuffle (C++11).

Danny_ds
  • 11,201
  • 1
  • 24
  • 46
  • @amdn, probably different, but not necessarily *much* different, because only a few bits (maybe just one) of the seed value have changed. The generator is still in a very similar state. I once worked with a shell script that picked a random item from a list by piping it through something like `shuf | head -n1`, and I noticed that if I ran it multiple times in quick succession, certain values were chosen noticeably more often than others. If I waited a while and did the same thing later, other values would be chosen frequently instead. – Wyzard Jan 20 '16 at 03:14
  • @Wyzard that's possible, rand() is usually implemented as a linear congruential generator (https://www.wikiwand.com/en/Linear_congruential_generator), depending on how many random bits it provides, and how many random bits the program uses, you may see patterns when the seeds differ by 1. – amdn Jan 20 '16 at 03:31
0

Every time you call srand() with a different value, you initialize the random number generator to return a different sequence of values.

Just call srand() again in the same way. Since the time value will likely be different, you will get a different sequence of results from rand().

If it is possible you need to do this before the time() value has changed, you can use: srand(time(NULL)+rand());

It's a while since I last wrote C++, so I'm not sure if you'll need to cast one or the other values before doing the addition, being that they're an int and a time_t.

JRR
  • 66
  • 4
0

For *nix system, you can try this one

unsigned seed;

read(open("/dev/urandom", O_RDONLY), &seed, sizeof(seed));
srand(seed);

For Windows, RtlGenRandom will give you an array of random bytes, which can be used as seed. Or just be used as a pseudo-random number.

zangw
  • 43,869
  • 19
  • 177
  • 214