Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate "random" but also "unique" numbers?

Tags:

c#

random

How are random numbers generated.? How do languages such as java etc generate random numbers, especially how it is done for GUIDs.? i found that algorithms like Pseudorandomnumber generator uses initial values.

But i need to create a random number program, in which a number once occurred should never repeats even if the system is restarted etc. I thought that i need to store the values anywhere so that i can check if the number repeats or not, but it will be too complex when the list goes beyond limits.?

like image 960
SyncMaster Avatar asked May 26 '09 10:05

SyncMaster


2 Answers

First: If the number is guaranteed to never repeat, it's not very random.

Second: There are lots of PRNG algorithms.

UPDATE:

Third: There's an IETF RFC for UUIDs (what MS calls GUIDs), but you should recognize that (U|G)UIDs are not cryptographically secure, if that is a concern for you.

UPDATE 2:

If you want to actually use something like this in production code (not just for your own edification) please use a pre-existing library. This is the sort of code that is almost guaranteed to have subtle bugs in it if you've never done it before (or even if you have).

UPDATE 3:

Here's the docs for .NET's GUID

like image 185
Hank Gay Avatar answered Nov 12 '22 18:11

Hank Gay


There are a lot of ways you could generate random numbers. It's usually done with a system/library call which uses a pseudo-number generator with a seed as you've already described.

But, there are other ways of getting random numbers which involve specialized hardware to get TRUE random numbers. I know of some poker sites that use this kind of hardware. It's very interesting to read how they do it.

like image 36
Pablo Santa Cruz Avatar answered Nov 12 '22 18:11

Pablo Santa Cruz