Because a project requires proportional random allocation. I can search in Baidu: calculate the probability by percentage. The results are all messy code. I found a seemingly usable one. After a rough look, it seemed quite complicated. I analyzed the code carefully and found a very serious Bug. So I wrote one myself and shared it with you.
Because a project requires proportional random allocation. I can search in Baidu: calculate the probability by percentage. The results are all messy code. I found a seemingly usable one. After a rough look, it seemed quite complicated. I analyzed the code carefully and found a very serious Bug. So I wrote one myself and shared it with you.
Because a project requires proportional random allocation. I can search in Baidu: calculate the probability by percentage. The results are all messy code.
I found a seemingly usable one. After a rough look, it seemed quite complicated. I analyzed the code carefully and found a very serious Bug.
So I wrote one myself and shared it with others.
The php version, of course, is easy to handle in other languages after understanding the ideas.
Suppose there are four options: a accounts for 10%, B accounts for 20%, C accounts for 30%, and d accounts for 40%. The principle is to obtain the random number and then find the interval.
Of course, the number of options can be any.
By default, the sum is 100%. If you need another number, modify the range of the random number.
This algorithm is relatively simple and efficient.
Of course, because it is rand (), a pseudo-random number is generated instead of a real random number.
/** --- A ------ B ------------ c --------- d * 1----11-----------30--------60---------100 * percentage probability selection */$ data = array ('A' => 10, 'B' => 20, 'c' => 30, 'D' => 40); echo randomSelect ($ data); function randomSelect (& $ array) {$ datas = $ array; if (! Is_array ($ datas) | count ($ datas) = 0) return; asort ($ datas); // sort by size $ random = rand (1,100 ); $ sum = 0; $ flag = ''; foreach ($ datas $ key => $ data) {$ sum + = $ data; if ($ random <= $ sum) {$ flag = $ key; break;} if ($ flag = '') {// if the sum of the passed values is less than 100, the highest probability is obtained. $ Keys = array_keys ($ datas); $ flag = $ keys [count ($ keys)-1];} return $ flag ;}
Original article address: calculate the probability of PHP by percentage. Thanks to the original author for sharing.