概率计算函数,网上搜了很多都是这个,不过没看得懂这函数,求解下过程是怎样的~
这数组是id和相应的概率。
Array
(
????[1] => 1
????[2] => 5
????[3] => 10
????[4] => 12
????[5] => 22
????[6] => 50
)
为什么这样就能得到概率奖项的id呢??get_rand($arr);
function get_rand($proArr) {
????$result = '';
????//概率数组的总概率精度
????$proSum = array_sum($proArr);
????//概率数组循环
????foreach ($proArr as $key => $proCur) {
????????$randNum = mt_rand(1, $proSum);
????????if ($randNum <= $proCur) {
????????????$result = $key;
????????????break;
????????} else {
????????????$proSum -= $proCur;
????????}
????}
????unset ($proArr);
????return $result;
}
------解决办法--------------------
假设a:20% b:30% c:50%
$r=rand(1,100)
$r<=20 a获奖
20<$r<=(20+30) b获奖
(20+30)<=$r c获奖