根据概率分布得到结果

cho*_*sta 2 php math

在浏览器游戏中,我们有基于其概率发生的项目.

P(i1)= 0.8

P(i2)= 0.45

P(i3)= 0.33

P(i4)= 0.01

我们如何在php中实现一个基于其概率机会返回随机项的函数?

编辑

这些项目有一个名为rarity的属性,从1到100不等,表示发生概率.发生的项目是从特定类型的所有项目的集合中选择的.(以上给出的例子代表所有工件第1层)

Dan*_*ith 8

我不知道它是否是最好的解决方案,但是当我不得不解决这个问题时,这就是我发现的:

这篇博客文章中获取的功能:

// 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]; 
}
Run Code Online (Sandbox Code Playgroud)

示例电话:

$values = array('A','B','C');
$weights = array(1,50,100);

$weighted_value = weighted_random($values, $weights);
Run Code Online (Sandbox Code Playgroud)

它有点笨拙,因为显然需要单独提供值和重量,但这可能会被重构以满足您的需求.