Click to See Complete Forum and Search --> : generate uniqe random numbers in php


kku
March 7th, 2005, 05:19 AM
hi friends
i have face litle problem i e
i want to generate 5 numbers uot of 10,but that five numbers should not match
each other.
examlpe:
{9,5,6,4,3} is true
{8,5,2,8,6} is false b/c 8 is appears two times

blueday54555
March 7th, 2005, 09:41 AM
<?
$dublicate=0;

for($a=0;$a<5;$a++)
{
srand ((double)microtime()*1000000);

$tmp = rand(0,10);

for ($b=0;$b<$a;$b++)
{
if($rndar[$b] == $tmp)
$dublicate++;
}
if ($dublicate>0)
$a--;
else
$rndar[$a] = $tmp;

$dublicate=0;
}

for ($a=0;$a<5;$a++)
{
echo $rndar[$a]."<br>";
}
?>

bigBA
March 7th, 2005, 11:02 AM
one srand should do it :)

here's another little function

<?

function generateRandomNumbers($count,$min,$max, &$arr)
{
//check if count is bigger than the range of numbers between $min and $max
//this would lead to an endless loop...
if( $count > ($max - $min +1) )
{
return false;
}

do
{
$i = rand($min,$max);
}while( !in_array($i,$arr) );

$array[] = $i;

if( (--$count) > 0 )
{
return generateRandomNumbers($count,$min,$max,$arr)
}

return true;
}


srand ((double)microtime()*1000000);

generateRandomNumbers(5,0,10, $numbers = array() );

echo "<pre>";
print_r($numbers);
echo "</pre>";
?>