This article mainly introduces the PHP implementation of the number of prizes and the probability of the lottery function, involving PHP string, array of probability operations related operations skills, the need for friends can refer to the next
Specific as follows:
<?php/** a lottery class, accurate to one out of 10,000 * Three steps: 1. Accept an array of winning probabilities; 2. Accept a lottery seed; 3. Return the winning level */class lottery {/** winning probability array, automatically judging the number of prizes * Array key value and 100, Automatically calculate the probability of not winning, if the initial is more than 100 throws an error */protected $_rate = Array ();/** set the probability of winning, * @param array, the probability of winning, in the form of an array of */public function Setrate ($rate = Array (12.1)) {$this->_rate = $rate; if (Array_sum ($this->_rate) > 100)//Detect probability setting if there is a problem throw new Exception (' Winning rate upto 100% '); if (Array_sum ($this->_rate) < 100)//define the probability of the not winning case, the user gives the probability only and is 100, then ignores 0$this- >_rate[] = 100-array_sum ($this->_rate);} /** randomly generates a 1-10000 integer seed, which is submitted to the winning judgment function * @return int, sorted by incoming probability, returns the number of entries */public function runOnce () {return $this->judge (mt_ RAND (0, 10000));} /** according to the probability set, determine whether an incoming random value is winning * @param int, $seed 10000 of the random number * @return int, $i sorted by the probability of passing in, return the number of winning entries */protected function judge ($ Seed) {foreach ($this->_rate as $key = + $value) {$TMPARR [$key + 1] = $value * 100;} Multiply probabilities by 10 to randomly select, combine into $tmparr[0] = 0;foreach ($tmpArr as $key + $value) {if ($key > 0) {$tmpArr [$key] + = $TMPARR [$ke Y-1];}} for ($i = 1; $i < COUNT ($TMPARR); $i + +) {if ($TMPARR [$i-1] < $seed && $seed <= $tmpArr [$i]) {return $i;//Returns the number of items won (in order of probability)}}} $rate = array (2, 0.95, 4.55), $a = new lottery; $a->setrate ($rate); for ($i = 0; $i <= 10000; $i + +) {$b = $a->runonce () @ $rewards [$b]++;} unset ($rewards ["]); Echo array_sum ($rewards);? >
Related recommendations:
PHP algorithm for calculating lottery probability
Generate numbers by probability
JS implementation of digital probability calculation