0

I am looking to generate a series of random numbers that have a difference of at least 2 from the previous number that was generated. I thought that a simple function that would call itself would be the way to go - see code below...

function getRandomLength($previous){
    $x = rand(1,12);

    if(abs($x - $previous) > 2){
        return $x;
    } else {
        getRandomLength($previous);
    }
}

For whatever reason, this is not working out the way that I had hoped it would. Any help would be appreciated.

Thanks.

And for those wondering why I want random numbers that are slightly different, I'm building a deck. I need to cut the decking boards and I don't want the joint to line up, or have any perceivable pattern to them, hence, I turn to my trusty random number generator to help out...

4

2 回答 2

1

这里有两个问题:

function getRandomLength($previous){
    $x = rand(1,12);

    if(abs($x - $previous) > 2){

第一个问题在这里 - 你> 2在你的意思时使用>= 2,例如,如果差异是两个或更多,那么它很好。

        return $x;
    } else {
        getRandomLength($previous);

第二个问题在这里 - 您再次调用该方法,但您没有返回调用它的结果,因此该方法的结果将是一个无用的null.

此外,您不应该将方法编码为递归,它应该是迭代的,因为它不需要递归逻辑。

    }
}
于 2013-06-12T23:22:16.587 回答
-1

由于您需要至少 2 的偏移量,因此选择一个从 0 开始的随机数并将其加 2。因为它是一个偏移量,所以你将它添加到之前的值(但我相信你可以弄清楚)。

于 2013-06-12T23:20:12.510 回答