Re: unique random number
| From: | Richard Jones | Date: | Tue, 08 Aug 2000 16:12:38 +0000 |
| Subject: | Re: unique random number | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-10727@lists.php.net to get a copy of this message | ||
On Tue, 08 Aug 2000, you wrote:
> Bas Verschaar wrote:
> > Hi,
> >
> > Every time i create a page, i want a random number (0..9) to be
> > generated but it may not be the same number as the previous number
> >
> > so:
> >
> > srand((double)microtime()*1000000);
> > $number = rand(0,9);
> >
> > with this code sometimes the value of $number is the same as the
> > previous number
> > is it in some way possible to solve this problem without using a
> > database?
>
> ... you could use some other "random numbers" like microtime, time,
> hhost_adr ect. and calculate them into the number somehow. You could also
> use a piece of the number you get from uniquid (see php-manual).
By the nature of "random", you are allowing for the possibility that the same
number comes up twice in a row. If it didn't, your system would not be truly
random. You could solve this problem, I think, by passing the last number
you generated to the script, and testing to see if the new random number is
the same or not. If it is, then discard it, run the script again, and again
and again until it's not the same. It's a bit un-elegant, and a bit brute
force, but it should do it. It also incorporates the danger that the script
will run forever, but if you calculate the probability, you'll discover it's
very very small indeed. Of course, depending on how you're doing this, it
may not be possible to use the above method.
Regards,
Richard