我正在尝试创建一个随机数生成器,它将根据其不断变化的动态概率生成数字。基本上它的功能是它会从页面中选择浏览次数最多的帖子到索引页面并显示它。因此,浏览次数最多的页面有它的计数器。在索引页面上,我使用此计数器并希望根据计数器生成一个随机数,该计数器将作为概率。计数器越高,机会越大。到目前为止,我的函数看起来像这样,但我想知道 PHP 中是否有任何内置函数,或者如何使它更好更高效:
private function randomWithProbability($chance, $num, $range = false)
{
/* first generate a number from 1 to 100 and see if that number is in the range of chance */
$rand = mt_rand(1, 100);
if ($rand <= $chance)
{
/* the number should be returned */
return $num;
}
else
{
/* otherwise return a random number */
if ($range !== false)
{
/* make sure that this number is not same as the number for which we specified the chance */
$rand = mt_rand(0, $range-1);
while ($rand == $num)
{
$rand = mt_rand(0, $range-1);
}
return $rand;
}
}
}
$range 只是生成不属于机会的数字的正常范围。
感谢您的帮助。