views:

1971

answers:

3

I want to generate unique random number sequence in QT, Using QDateTime::currentDateTime().toTime_t() as seed value, will qrand() generate unique random numbers?

+1  A: 
balpha
Qt documentation says qrand() returns a value between 0 and RAND_MAX, if qrand() is invoked at different times during the execution of the program, will it generate unique numbers.?-Thanks.
Suresh
No. Not neccessarily.
balpha
qrand is just a pseudo random generator, it gives no guarantee the valueas are unique. You'd have to ensure that yourself, e.g. storing the numbers generated in a set.
nos
A: 

According to the Qt Documentation, QRand is just a thread-safe version of the standard rand(), I wouldn't assume the method used is any more secure/superior to that of rand() based on that description.

I think you need to use different terminology than 'unique' random numbers (no Psuedo-Random Number Generator will produce a unique stream, as input X will always produce output Y). What's the actual situation?

Kitsune
There a server process running, wanted to assign unique random value as session id when a client connects to it.
Suresh
Ah... I see what you're wanting now. qrand() *alone* won't work for that, but you can use qrand() in addition to a table of previously assigned (active) session ids to make sure that the value is unique before sending it to the client. Depending on your needs, that might be enough. Although, you might want to look into alternative PRNGs- such as reading from /dev/urandom on Linux, as a replacement for qrand().
Kitsune
A: 

Depending on how you store your session ids, you can generated a (mostly) guaranteed unique identifier by using a UUID. See the documentation for QUuid. Also be aware of this (bold added):

You can also use createUuid(). UUIDs generated by createUuid() are of the random type. Their QUuid::Version bits are set to QUuid::Random, and their QUuid::Variant bits are set to QUuid::DCE. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated by createUuid() will not be unique. But it is a very small chance.

I can vouch for the fact that those generated UUIDs won't necessarily be unique, so if you do need them to be unique, look into libuuid or something similar.

Caleb Huitt - cjhuitt