根据概率分布获取结果 [英] Get result based on probability distribution
问题描述
在浏览器游戏中,我们根据物品的概率出现物品.
In a browser game we have items that occur based on their probabilities.
P(i1)= 0.8
P(i1) = 0.8
P(i2)= 0.45
P(i2) = 0.45
P(i3)= 0.33
P(i3) = 0.33
P(i4)= 0.01
P(i4) = 0.01
我们如何在php中实现一个根据概率概率返回随机项目的函数?
How do we implement a function in php that returns a random item based on its probability chance?
这些物品具有一个称为稀有度的属性,其范围从1到100不等,代表发生的可能性.发生的项目是从某种类型的所有项目的集合中选择的. (例如,上面给出的示例代表了所有工件第1层)
The items have a property called rarity which varies from 1 to 100 and represents the probability to occcur. The item that occurs is chosen from a set of all items of a certain type. (e.x the given example above represents all artifacts tier 1)
推荐答案
我不知道它是否是最好的解决方案,但是当我不得不解决这一问题时,这就是我发现的:
I don't know if its the best solution but when I had to solve this a while back this is what I found:
该功能取自此博客帖子:
// 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);
这有点笨拙,因为显然需要分别提供值和权重,但是可以将其重构为适合您的需求.
It's somewhat unwieldy as obviously the values and weights need to be supplied separately but this could probably be refactored to suit your needs.
这篇关于根据概率分布获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!