This article mainly introduces the algorithm of winning probability in PHP and JS. It has certain reference value. Now I share it with you. Friends in need can refer to the
classic probability algorithm.
Now there is an array: [10, 20, 30, 40].
Assume that the corresponding probability of winning is: 10% for the special prize, 20% for the first prize, 30% for the second prize, 40% for the third prize, a total of 100%.
When the algorithm starts, a value $value is selected from the array, and then a number $rand is randomly selected from the probability space of 1-100.
Compare $value and $rand. If $rand is within the $value probability range, directly return the key corresponding to $value.
If not, subtract the $value value from the value of the probability space.
In this example, after the first judgment, 10 is subtracted, which means that the second time is filtered in the range of 1-90.
After filtering until the end, there will always be a number that meets the requirements.
It is equivalent to touching something in a box.
The first one is not, the second is not, and the third is not, then the last one must be.
This algorithm is simple and very efficient.
PHP implementation
<?php function getRand($arr) { $result = ''; //概率数组的总概率精度 $sum = array_sum($arr); //概率数组循环 foreach ($arr as $key => $value) { $rand = mt_rand(1, $sum); if ($rand <= $value) { $result = $key; break; } else { $sum -= $value; } } unset ($arr); return $result; } 使用范例: $a = [10, 20, 30, 40]; // 输出3的概率最大 echo 'PHP:' . getRand($a);
Javascript implementation
<script> function getRand(arr) { var result = 0; var sum = arr.reduce(function(a, b) { return a + b; }); for (index in arr) { rand = Math.round(Math.random() * (sum - 1) + 1); if (rand <= arr[index]) { return index; } else { sum -= arr[index]; } } return result; } // 使用示例,输出2的概率最大 var a = [10, 20, 30, 40]; document.write('<br />Javascript:' + getRand(a)); </script> 使用范例: // 使用示例,输出3的概率最大 var a = [10, 20, 30, 40]; document.write('<br />Javascript:' + getRand(a));
The above is the entire content of this article, I hope it will be helpful to everyone’s learning Help, please pay attention to the PHP Chinese website for more related content!
Related recommendations:
How to quickly generate modern forms with PHP
php simply uses the shmop function to create shared memory and reduce Server load
The above is the detailed content of PHP and JS lottery winning probability algorithm. For more information, please follow other related articles on the PHP Chinese website!