3

I'm running rand() 3 times, and I want to exclude the first two results from the possibilities of the function. Like if it hit 1 and 5, I want the next rand() to exclude 1 and 5 from its range. How would I do this?

AKor
  • 8,550
  • 27
  • 82
  • 136
  • 6
    Then it's not random anymore though. :o) – deceze Feb 28 '11 at 07:34
  • In before xkcd and/or 4. Oh, also, consider `mt_rand` instead of `rand`. – Charles Feb 28 '11 at 07:43
  • @Charles You're forgetting Nine, Nine, Nine, Nine, Nine, Nine. – deceze Feb 28 '11 at 08:01
  • Possible duplicate of [How to get a random value from 1~N but excluding several specific values in PHP?](http://stackoverflow.com/questions/2698265/how-to-get-a-random-value-from-1n-but-excluding-several-specific-values-in-php) – Don't Panic Jun 03 '16 at 16:16

3 Answers3

5

How about:

do {   
    $rand_number = rand();

}while(in_array($rand_number, array(1,5));
cypher
  • 6,822
  • 4
  • 31
  • 48
1

If you want to generate three unique random(ish) numbers, you could use:

$totalNumsNeeded = 3;
$randoms = array();
while (count($randoms) < $totalNumsNeeded) {
    $random = rand($min, $max);
    if (!in_array($random, $randoms)) {
        $randoms[] = $random;
    }
}
Eric G
  • 4,018
  • 4
  • 20
  • 23
0
$last[];

for ($i = 0; $i < 10; $i++) {
  $min = getLow($last);
  $max = getHigh($last);

  $myrand =  rand ( $min, $max )
  $last[i] = $myrand;
}

You will need to build the two functions to itterate through the $last array and return the variables you want it to return... or if you are only looking for the last two, you could initialize $min and $max outside of the loop and set them on each itteration. This will continually tighten your random range though.

Another solution may be

$last;
While (true) {
  $myRand = rand();
  if ($myRand != $last) {
    $last = $myRand;
    break;
  }

}
david
  • 726
  • 1
  • 5
  • 10