I want to generate unique random number sequence in QT, Using QDateTime::currentDateTime().toTime_t() as seed value, will qrand() generate unique random numbers?
3 Answers
No. qrand
can only generate as many unique numbers as fit into an integer, so -- whatever the implementation -- you cannot count on uniqueness.
Also, knowing that a different seed creates a different random integer would yield a level of predictability that effectively makes qrand
not random anymore.
Edit: I swear I'm not trying to make fun of you by posting a cartoon; I think this is a quite good explanation of the problem:
(source: dilbert.com)

- 21,988
- 13
- 81
- 109

- 50,022
- 18
- 110
- 131
-
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 Jul 29 '09 at 17:08
-
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 Jul 29 '09 at 17:15
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 bycreateUuid()
are of the random type. TheirQUuid::Version
bits are set toQUuid::Random
, and theirQUuid::Variant
bits are set toQUuid::DCE
. The rest of the UUID is composed of random numbers. Theoretically, this means there is a small chance that a UUID generated bycreateUuid()
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.

- 14,785
- 3
- 42
- 49
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?

- 9,101
- 2
- 25
- 24
-
There a server process running, wanted to assign unique random value as session id when a client connects to it. – Suresh Jul 29 '09 at 17:27
-
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 Jul 29 '09 at 17:39