0

I want to create 8 random integers, that are unique and in the range between 0 and 99.

Is there a neater solution, than the one that I thought of?

<?php


do {

  $rnd1 = rand(0,99);
  $rnd2 = rand(0,99);
  $rnd3 = rand(0,99);
  $rnd4 = rand(0,99);
  $rnd5 = rand(0,99);
  $rnd6 = rand(0,99);

} while (($rnd1 == $rnd2) || 
         ($rnd1 == $rnd3) || 
         ($rnd1 == $rnd4) || 
         ($rnd1 == $rnd5) || 
         ($rnd1 == $rnd6) || 
         ($rnd2 == $rnd3) || 
         ($rnd2 == $rnd4) || 
         ($rnd2 == $rnd5) || 
         ($rnd2 == $rnd6) || 
         ($rnd3 == $rnd4) || 
         ($rnd3 == $rnd5) || 
         ($rnd3 == $rnd6) || 
         ($rnd4 == $rnd5) || 
         ($rnd4 == $rnd6) || 
         ($rnd5 == $rnd6)    );


?>
Leon
  • 45
  • 7

3 Answers3

2

Try the code below.
It will create an array containing 8 random values between 0 and 99 while checking if they have been added already to ensure they are unique across.

$numbers = array();
while ( count($numbers) <= 8 ) {
    $x = mt_rand(0,99); 
    if ( !in_array($x,$numbers) ) {
        $numbers[] = $x;
    }
}
print_r($numbers);

Also see these two Q&A's about using mt_rand vs. rand
Difference between mt_rand() and rand()
What's the disadvantage of mt_rand?

Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42
1

This is an optimized version that relies on the array indexes. The complexity of this solution is linear rather than n2 as in @AlexAndrei's answer. It relies on using array indexes as the guarantee there are no duplicates so there is no need to add the overhead of in_array.

$random_numbers = [];

do {
  $rand = rand(0, 99);
  $random_numbers[$rand] = $rand;
} while( count($random_numbers) < 9 );

$random_numbers = array_values($random_numbers); // This strips the keys

print_r($random_numbers);

If you are using a foreach you can even drop the array_values call which would also increase the speed of your code, but the numbers in the array will be in the form: [ a => a, b => b, ... ]

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86
  • Though you can use `mt_rand()` instead of `rand()` which should theoretically speed up the avarage generation process because of `mt_rand()`'s higher entropy. – Itay Grudev Oct 06 '15 at 11:43
-1
$rnds = [];

do {
  $newRnd = rand(0, 99);
  $rnds[] = $newRnd;
} while(in_array($newRnd, $rnds) && count($rnds) < 9);

print_r($rnds);
marekful
  • 14,986
  • 6
  • 37
  • 59
  • If there is a duplicate, this would only do another itteration of the (do while) loop, not actually remove/overwrite it. Stub the `rand` with `5` and you will see that I am correct. – Itay Grudev Oct 06 '15 at 11:32