Forum Moderators: coopster

Message Too Old, No Replies

PHP rand()

avoiding repeating numbers

         

StoutFiles

7:00 pm on May 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all.

I'd like to generate 12 random numbers in a field of 180. However, I cannot have any of the 12 numbers generated be the same number. Is there any way to do this without generating a number, then having to compare it to the second, then compare both to the third, etc.?

willybfriendly

7:56 pm on May 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You could randomly pull elements from an array, replacing the one pulled with a marker of some sort.

$nums = array(0,1,2,3,4,5,...,180);

function randNum()
{
global $nums;
$rnd = rand(0, 180);
$num = $nums[$rnd];
if(is_int($num)
{
unset $nums[$rnd];
return $num;
}
else
{
randNum();
}
}

$num = randNum();

Untested, so use at your own risk...

eelixduppy

8:16 pm on May 28, 2009 (gmt 0)



That could work. Or you can use shuffle [php.net]() to shuffle the array of numbers and just grab the first 12 of them.

For example:


$i = 0;
$nums = array();
#
for($i; $i <= 180; $i++)
$nums[] = $i;
#
shuffle($nums);
#
for($i = 0; $i < 12; $i++)
echo $nums[$i] . '<br>';

I haven't tested this yet but I'm not sure if a solution like this would be any faster or slower than generating random numbers and checking them against the array of already selected random numbers. My guess is the more random numbers you need to more intensive an algorithm like that would be. The one presented above should be constant regardless of how many numbers you need. Experiment with it a bit and see what you come out with.

StoutFiles

9:10 pm on May 28, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I played with the shuffle() a bit and ended up with this.

$num = range($min, $max);
shuffle($num);
$rand1 = $num[0];
$rand2 = $num[1];
/*and so on*/

I think this will do it. Thanks for the help!