Php lottery probability algorithm
/** The lottery drawing principle with different probabilities is to divide the 0 to * (total proportion) intervals based on the proportion of the entire item, then, the random number seed is used to generate a number in 0-* to determine the range in which the number falls, and the interval corresponds to the item drawn. * The random number is theoretically equal in probability, so the quantity in the corresponding range reflects the different probability of the lottery. */Function get_rand ($ proArr) {$ result = array (); foreach ($ proArr as $ key => $ val) {$ arr [$ key] = $ val ['V'];} $ proSum = array_sum ($ arr); // calculate the total weight $ randNum = mt_rand (1, $ proSum); $ d1 = 0; $ d2 = 0; for ($ I = 0; $ I <count ($ arr); $ I ++) {$ d2 + = $ arr [$ I]; if ($ I = 0) {$ d1 = 0 ;} else {$ d1 + = $ arr [$ i-1];} if ($ randNum >=$ d1 & $ randNum <= $ d2) {$ result = $ proArr [$ I] ;}} unset ($ arr); return $ result ;} /** use this method more often */function get_rand1 ($ proArr) {$ result = array (); foreach ($ proArr as $ key => $ val) {$ arr [$ key] = $ val ['V'];} // total probability of the probability array $ proSum = array_sum ($ arr); asort ($ arr ); // probability array loop foreach ($ arr as $ k => $ v) {$ randNum = mt_rand (1, $ proSum); if ($ randNum <= $ v) {$ result = $ proArr [$ k]; break;} else {$ proSum-= $ v ;}} return $ result ;}
/** Prize array * prize id, name, proportion */$ arr = array ('id' => 1, 'name' => 'grand prize ', 'V' => 1), array ('id' => 2, 'name' => 'first prize ', 'V' => 5 ), array ('id' => 3, 'name' => 'Second prize ', 'V' => 10), array ('id' => 4, 'name' => 'third prize ', 'V' => 12), array ('id' => 5, 'name' => '4th prize ', 'V' => 22), array ('id' => 6, 'name' => 'No Winner', 'V' => 50 )); test result (10000 times): get_rand (): count_1: 0 count_2: 490 count_3: 1021 count_4: 1172 count_5: 2172 count_6: 5145 grand prize winning rate: 0get_rand1 (): count_1: 92 count_2: 477 count_3: 1017 count_4: 1195 count_5: 2264 count_6: 4955 overall feeling get_rand1 () is more accurate ......