Page 1 of 1

generate 3 random (not same) numbers within 1 to 20

Posted: Thu Jan 08, 2009 1:30 am
by mit
i need to generate 3 number like 4,15,19 or 17,01,11 the numbers should not be same
can any one help me?

Re: generate 3 random (not same) numbers within 1 to 20

Posted: Thu Jan 08, 2009 1:50 am
by requinix
Use range to create an array of numbers one through twenty and array_rand to pick three random ones (they will be unique).

Re: generate 3 random (not same) numbers within 1 to 20

Posted: Thu Jan 08, 2009 2:00 am
by Apollo

Code: Select all

function GetRandomNrs( $min=1, $max=20, $num=3 )
{
    if ($num > $max-$min+1) $num = $max-$min+1;
 
    $result = array();
    for ($i=0; $i<$num; $i++)
    {
        do
        {
            $x = mt_rand($min,$max);
        }
        while (in_array($x,$result));
        $result[] = $x;
    }
    return $result;
}
If you'd be picking random unique values from an array, the array_rand function is your friend.

For low numbers of possibilities (as in your case 1 to 20), the range function mentioned by tasairis is easier. If you want to pick 3 numbers between 1 and 100.000.000, the above function is faster.

Re: generate 3 random (not same) numbers within 1 to 20

Posted: Thu Jan 08, 2009 2:22 am
by mit
thx a lot , it s working perfectly ... :drunk: