Home > Article > Backend Development > Introduction to PHP random probability calculation function
This article mainly introduces the introduction of PHP random probability calculation function. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.
In game development, you will often encounter To the scenario of calculating probability
The following code is the simplest example of calculating a random result based on a given probability
<?php //a出现的概率是10%,b是20%,c是30%,d是40% $pro = [ 'a' =>10, 'b' =>20, 'c' =>30, 'd' =>40 ]; function proRand($pro) { $ret = ''; $sum = array_sum($pro); foreach($pro as $k=>$v) { $r = mt_rand(1, $sum); //echo $r . "\t" . $v . "\n"; if($r <= $v) { $ret = $k; break; }else{ $sum = max(0, $sum - $v); } } return $ret; } echo proRand($pro);
More complex ones may add weights to the probability.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
How to read large excel file data with PHP
The above is the detailed content of Introduction to PHP random probability calculation function. For more information, please follow other related articles on the PHP Chinese website!