1

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;
}
5
  • 1
    Maybe I'm just blind, but I don't see any recursion in the above. Could you point it out? Commented Jan 27, 2014 at 23:06
  • while(array_search($number,$exceptions) === FALSE) but 'im thinking i just need a return $number inside that if loop Commented Jan 27, 2014 at 23:07
  • Recursion is when a function calls itself. That's not happening above. Commented Jan 27, 2014 at 23:08
  • whats with the print_r ? the code above does not work as is Commented Jan 27, 2014 at 23:09
  • theres nothing recursive. its an iteration. if is a statement not a loop. Commented Jan 27, 2014 at 23:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

array_search returns the key for needle if it is found in the array, FALSE otherwise. So it should work fine, I tried in_array() same problem.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.