This is a very classical probability algorithm function:
Function get_rand ($PROARR) { $result = '; Total probability accuracy of //probability array $proSum = array_sum ($PROARR); //probability array loop foreach ($proArr as $key => $proCur) { $randNum = mt_rand (1, $proSum) //decimation random number if ($randNum <= $proCur) { $result = $key; //Results break; } else { $proSum -= $proCur; } } unset ($PROARR); return $result; }
Suppose: We have such an array: a prize probability 20%,b prize probability 30%,c prize probability 50%
$prize _arr =array (' A ' =>20, ' B ' =>30, ' C ' =>50);
Simulation function Execution Process:
Total probability accuracy is 20+30+50=100
First-time array loop, $procur =20
Assuming the extracted random number rand (1,100), assume that pumping to $randnum=55
If Judgment-------
If $randnum<=20, then result=a
Otherwise into the next cycle, the total probability accuracy becomes 100-20=80
Second array loop, $procur =30
Assuming the decimation of the random number rand (1,80), assume that pumping to $randnum=33
If Judgment---------
If $randnum<=30, then result=b
Otherwise into the next cycle, the total probability accuracy becomes 80-30=50
The third array loop, $prosur = 50;
Assuming the extracted random number rand (1,50), no matter how pumped, the random number will be < or = 50,
then draw result=c;
Because the sample does not change, although it is possible to extract more than one random number, the probability is constant.
Or you can do this:
function get_rand ($arr) { $pro _sum=array_sum ($arr); $rand _num=mt_rand (1 , $pro _sum); $tmp _num=0; foreach ($arr as $k = $val) { if ($rand _num<=$ val+ $tmp _num) { $n = $k; break; }else { $tmp _num+= $val; } } return $n; }
http://denghai260.blog.163.com/blog/static/7268640920128244332285/
PHP Probabilistic algorithm