random numbers not repeat

Alles, was PHP betrifft, kann hier besprochen werden.

random numbers not repeat

Postby aj123cd » 05. October 2009 21:35

Is there a simple way to do this?

I want to pick 3 numbers between 1 and 10 randomly. But I want to make sure there is no chance for the same number showing up.

Correct 4,10,7

Incorrect 4,4,10
can any one tell me how can i do it?
thanks
aj123cd
 
Posts: 62
Joined: 03. June 2009 08:19
Location: London,UK

Re: random numbers not repeat

Postby Xardas der Dunkle » 05. October 2009 21:55

Code: Select all
<?php
function getRandomNumber
($min, $max) {
    static $alreadyExists = array();

    // Avoid endles-loop
    if(count($alreadyExists) < ($max+$min)) {
        do {
            $i = rand($min, $max);
        } while(isset($alreadyExists[ $i ]));

        $alreadyExists[ $i ] = true;

        return $i;
    } else {
        return null;
    }
}

for(
$i=0; $i<20; $i++) {
    var_dump(getRandomNumber(0, 10));
}
 
User avatar
Xardas der Dunkle
 
Posts: 482
Joined: 09. March 2008 19:40
Location: /var/www

Re: random numbers not repeat

Postby Wiedmann » 05. October 2009 22:09

for example:
Code: Select all
<?php
$randNums 
= array();
while (!= count($randNums)) {
    $randNums[mt_rand(110)] = null;
}
$randNums array_keys($randNums);

var_dump($randNums);
?>


A function might also be a good idea (@Xardas der Dunkle) ;-):
Code: Select all
<?php
function get_unique_range
($count, $min, $max)
{
    if (($max - $min + 1) < $count) {
        return false;
    }

    $randNums = array();
    while ($count != count($randNums)) {
        $randNums[mt_rand($min$max)] = null;
    }
    
$randNums array_keys($randNums);    

    return $randNums
;
}

var_dump(get_unique_range(3, 1, 10));
?>
Wiedmann
AF Moderator
 
Posts: 17102
Joined: 01. February 2004 12:38
Location: Stuttgart / Germany

Re: random numbers not repeat

Postby aj123cd » 06. October 2009 06:58

Xardas der Dunkle , Wiedmann
Thank you 4u help.
:D :D :D :D :D :D
aj123cd
 
Posts: 62
Joined: 03. June 2009 08:19
Location: London,UK


Return to PHP

Who is online

Users browsing this forum: No registered users and 21 guests