Dawson Irvine
Dawson Irvine

Reputation: 334

Not returning value although appears to be working

I have the following PHP code which produces random numbers using rand() and to unsure there are no duplicates until the max int, a session which tracks what numbers have been used. The max should never get too high so speed if the randoms are larger is not a problem and this sort of works fine so far. HOWERVER...

function random($min,$max) {
    if(count($_SESSION["randoms"])==5) {
        unset($_SESSION["randoms"]);
    }
    $rand = rand($min,$max);
    echo "Chosen Random: $rand<br>";
    if(@in_array($rand,$_SESSION["randoms"]) && count($_SESSION["randoms"])!=0) {
        echo "<strong>In Array: </strong>Do It Again<br>\n";
        random($min,$max);
    }
    else {
        echo "<strong>All Good </strong> Return $rand as number and include in array!<br>\n";
        $_SESSION["randoms"][] = $rand;
        return $rand;
    }
}

I have a few echo blocks in there to help debug. Everything works fine however when the random is called on the recursive it continues going until it finds a number not in the array and echos "All Good" and adds it to the array, but doesn't return it. If the number was not in the array to begin with it returns it fine. I am confused as to why it will echo the "All Good" and add it to the array but not return it to use in the rest of the script.

Upvotes: 0

Views: 44

Answers (1)

sharafatalee
sharafatalee

Reputation: 134

Your implementation of recursion is wrong. Your return is returning value to a recursive call but then what next ? Now way around to return final result.

By the way complexity of recursive algo is more. You can perform this task with do while as well.

function random($min,$max) {
if(count($_SESSION["randoms"])==5) {
    unset($_SESSION["randoms"]);
}
do{
   $rand = rand($min,$max); 

 }while(@in_array($rand,$_SESSION["randoms"]));   

$_SESSION["randoms"][] = $rand;        
return $rand;

}

I have not tested it right now, But this is how i usually do it.

Upvotes: 1

Related Questions