在浏览器游戏中,我们有根据概率发生的项目。
P(i1) = 0.8
P(i2) = 0.45
P(i3) = 0.33
P(i4) = 0.01
我们如何在 php 中实现一个函数,根据它的概率返回一个随机项?
编辑
这些项目具有称为稀有性的属性,该属性从 1 到 100 不等,表示发生的概率。出现的项目是从一组特定类型的所有项目中选择的。(例如,上面给出的示例代表所有工件第 1 层)
我不知道它是否是最好的解决方案,但是当我不得不解决这个问题时,这就是我发现的:
取自这篇博文的函数:
// Given an array of values, and weights for those values (any positive int) 
// it will select a value randomly as often as the given weight allows. 
// for example:
// values(A, B, C, D)
// weights(30, 50, 100, 25)
// Given these values C should come out twice as often as B, and 4 times as often as D. 
function weighted_random($values, $weights){ 
    $count = count($values); 
    $i = 0; 
    $n = 0; 
    $num = mt_rand(0, array_sum($weights)); 
    while($i < $count){
        $n += $weights[$i]; 
        if($n >= $num){
            break; 
        }
        $i++; 
    } 
    return $values[$i]; 
}
示例调用:
$values = array('A','B','C');
$weights = array(1,50,100);
$weighted_value = weighted_random($values, $weights);
这有点笨拙,因为显然需要单独提供值和权重,但这可能会被重构以满足您的需求。
试图了解 Bulk 的功能是如何工作的,这是我根据 Benjamin Kloster 的回答所理解的:
https://softwareengineering.stackexchange.com/questions/150616/return-random-list-item-by-its-weight
在 0 到 sum(weights) 的范围内生成一个随机数 n,在本例中为 $num,因此可以这样说:weights(30, 50, 100, 25)。
总和是 205。
现在 $num 必须是 0-30 才能得到 A,
30-80拿B
80-180获得C
和 180-205 得到 D
While 循环查找 $num 落在哪个区间。