Suitable for lottery system
- /*
- * A lottery category, accurate to one ten thousandth
- * Three steps: 1. Accept a winning probability array; 2. Accept a lottery seed; 3. Return the winning level
- * /
- class Lottery {
- /*
- * Winning probability array, automatically determine the number of awards
- * The sum of the array key values is 100, automatically calculate the probability of not winning, if the initial value exceeds 100, an error will be thrown
- */
- protected $_rate = array();
- /*
- * Set the winning probability,
- * @param Array, the winning probability, passed in as an array
- */
- public function setRate($rate = array(12.1, 34) ) {
- $this->_rate = $rate;
- if (array_sum($this->_rate) > 100)//Detect whether there is a problem with the probability setting
- throw new Exception('Winning rate upto 100%') ;
- if (array_sum($this->_rate) < 100)
- //Define the probability of not winning. When the probability given by the user only sums to 100, ignore 0
- $this->_rate[] = 100 - array_sum($this->_rate);
- }
-
- /*
- * Randomly generate an integer seed from 1 to 10000 and submit it to the winning judgment function
- * @return int, sorted by the incoming probability, return the winning The number of items
- */
-
- public function runOnce() {
- return $this->judge(mt_rand(0, 10000));
- }
-
- /*
- * According to the set probability, judge an incoming Whether the random value wins the prize
- * @param int,$seed Random number within 10000
- * @return int,$i Sort by the passed probability and return the number of winning items
- */
-
- protected function judge($seed) {
- foreach ($this->_rate as $key => $value) {
- $tmpArr[$key + 1] = $value * 100;
- }
- //Multiply the probability by ten and accumulate it for random selection, Combined into
- $tmpArr[0] = 0;
- foreach ($tmpArr as $key => $value) {
- if ($key > 0) {
- $tmpArr[$key] += $tmpArr[$key - 1];
- }
- }
- for ($i = 1; $i < count($tmpArr); $i++) {
- if ($tmpArr[$i - 1] < $seed && $seed < = $tmpArr[$i]) {
- return $i; //Return the number of winning items (in order of setting probability)
- }
- }
- }
- }
- $rate = array(33, 20, 2, 0.95, 12, 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);
- ?>
-
-
-
-
-
-
- < ;thead>Run 10,000 times, compare the set probability and the number of winnings
-
Set the probability | The number of winnings |
-
% | |
-
% | |
-
% | |
-
% | |
-
%< /td> | |
-
% | |
-
| |
-
-
-
-
-
Copy code
|