Search code examples
c++randomunique

Generating Truly Random Numbers


Possible Duplicate:
Generating random numbers effectively

I need to generate random numbers in my C++ application. I know from reading these two articles --

http://www.cprogramming.com/tutorial/random.html

write a c function that generates one random number, or a pair of random numbers, or a triplet of random numbers given the particular ranges

-- that random numbers can be generated using srand() and rand() but in both cases the current time according to the system clock is used as a seed. But I read in the first article that rand() will create the same random numbers if the seed is the same. So if two different users ran my application at the same time then they would have the same random numbers. Which would be pointless because I need the random numbers to be unique for the most part. (I know they cant be truly 100% unique if they are generated randomly)

So my question is can I create a random seed not based on system time and if so how, why does rand() produce the same numbers with the same seed and is there a way to make rand() produce different numbers with the same seed, or is there any other way to generate random numbers?


Solution

  • Without using special hardware (and even then, it's debatable), there is no such thing as a truly random number generated by a computer.

    That being said; your only problem is: how do you generate your seeds such that two programs will not generate the same number. Using the current time as part of your seed is reasonable, but as you understand, it's not enough because two programs could generate their seed at the same time... so you need to augment your seed based on something that will be unique between the programs. Possibilities include process ID (which will differ if both programs are on the same computer), hardware mac address (which will differ if both programs are on different computers), or timing how long it takes the user to perform some task (which will generally differ as long as the user is human, not automation).