Dan Cech wrote:
...
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.
...
Depending on the number of results needed, building an array of all
possible combinations and then removing each when randomly selected is
another option. For an 8 digit base-10 pool, the memory required would
be huge. Sample code below. Can anyone calculate the break-even point at
which it is faster to use this vs the random guess method mentioned
above? :)
<?php
$digits=5; // change this to 8 if you have enough memory
$limit=pow(10,$digits);
$biglist=array();
// stuff the array
for ($x=0;$x<$limit;$x++) {
$biglist[$x]=$x;
}
// run through guesses
for ($x=0;$x<10;$x++) {
$pick=rand(0,count($biglist));
printf("random #=$x - %0{$digits}d\n",$biglist[$pick]);
array_splice($biglist,$pick,1);
}
?>
~Rolan
_______________________________________________
New York PHP User Group Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk
http://www.nyphp.org/show_participation.php