Question

I'm trying to generate a unique randomized array with exceptions, i got this far:

function rand_except($min, $max,$no_numbers, $except) {
   //loop until you get a unique randomized array without except number

  $end=false;
  while (!$end){
     $numbers = rand_array($min, $max,$no_numbers);//get unique randomized array
     if(!in_array($except,$numbers)){
       $end=true;   
       break;
     }

   }
return $numbers;
}

but now i want the function to loop until the except parameter isn't in the array

Was it helpful?

Solution

I suspect it would be easier to solve this problem by updating the rand_array function (or writing a modified version of it) to generate the array without the $except value to start with.

If that is not an option, here is one possible solution that doesn't involve calling the rand_array function over and over again:

$numbers = rand_array($min, $max-1, $no_numbers);
for ($i = 0; $i < count($numbers); $i++) {
  if ($numbers[$i] >= $except) {
    $numbers[$i] += 1;
  }
}

You call the rand_array function but specify one less than the actual maximum number you want in the array. Then you loop over the results, and any value that is greater than or equal to the $except value, you increment by 1.

This is assuming that the $except value is in the range $max to $max. If not, you can just return rand_array($min, $max, $no_numbers); as is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top