NYCPHP Meetup

NYPHP.org

[nycphp-talk] generate random unique 8-digit number

Dan Cech dcech at phpwerx.net
Tue Mar 10 11:54:22 EDT 2009


Chris Snyder wrote:
> Add a random number to a sufficiently deep timestamp (microseconds)
> and you will have a non-repeating random number. But you can't shorten
> it to 8 characters or whatever -- you have to keep the full timestamp
> in order to maintain non-repeatability.

Not really, if you add a random number then you can easily end up with 2
results that are the same unless the frequency with which you generate
numbers is less than the variation you're introducing, and at that point
why bother with the random number at all...

It is not possible to produce a fixed-length number/string which will
_never_ repeat, simply because you will run out of combinations
eventually.  Using 'random' values just means that you can't take the
previous number and add one to determine the next unused number.

If you're trying to generate relatively short pseudo-random IDs to
thwart guesses, then the simplest method is going to be the
previously-recommended approach of generating a random number and
checking if it has already been used, rinse and repeat until you find
one that has not.  This will get progressively slower as the number of
IDs generated grows, but is the only way you can be 100% sure of a truly
random ID which will never conflict.

If you go with a scheme like uuids then you can be sufficiently
confident (but never 100% sure) that they are not going to repeat.
However, if you try using some scheme to hash them down to 8 digits all
bets are off as you're going from 16^32 down to 10^8 combinations.

Dan



More information about the talk mailing list