0

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.

4

1 回答 1

1

您的递归实现是错误的。您的返回是将值返回给递归调用,但接下来呢?现在返回最终结果。

顺便说一句,递归算法的复杂性更高。您也可以使用 do while 执行此任务。

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;

}

我现在还没有测试过,但这是我通常的做法。

于 2013-10-31T05:13:28.043 回答