Reputation: 3091
I have this function which is supposed to generate random numbers and make sure they are not in the exceptions array, but I have this corner case:
It does not execute the while condition:
Exceptions Array
(
[0] => 84
[1] => 94
[2] => 46
)
print_r ouput : number generated is 46 we have a match number im going to return is 84
so it does the first check correctly but not the recursive check, so it returns to me a duplicate value 84, is my while condition wrong?
function randWithout($from, $to, array $exceptions) {
//sort($exceptions); // lets us use break; in the foreach reliably
echo '<pre>';
print_r($exceptions);
echo '</pre>';
$number = mt_rand($from, $to);
print_r('number generated is' . $number);
if(array_search($number,$exceptions) != FALSE)
{
echo 'we have a match';
do {
$number = mt_rand($from, $to);
} while(array_search($number,$exceptions) === FALSE);
}
print_r('number im going to return is'. $number);
return $number;
}
Upvotes: 1
Views: 990
Reputation: 9748
Ok here's what you should change it to:
$ex = [12,18,15];
for($i=0; $i<20;$i++) {
print randWithout(10,20,$ex) . PHP_EOL;
}
function randWithout($from, $to, array $exceptions) {
do {
$number = mt_rand($from, $to);
} while(in_array($number,$exceptions));
return $number;
}
Just tested it and it works.
Upvotes: 1
Reputation: 3091
changed to:
if(in_array($number,$exceptions) != FALSE)
{
echo 'we have a match';
do {
$number = mt_rand($from, $to);
} while(in_array($number,$exceptions));
}
Removed the == FALSE
clause from in_array, as it returns true if needle is found.
Upvotes: 0