An example of PHP probabilistic algorithm for lottery and random advertising

Source: Internet
Author: User
Tags foreach range

  Do site classes sometimes get an activity or something to allow users to participate, not only to attract users to register, but also improve the user activity of the site. At the same time to participate in the user will get a certain prize, there are 100% winners, there is a certain probability of winning, big such as the ipad, iphone5, small in the Q currency what the

Then we in the program will inevitably design to the algorithm, that is, according to a certain probability to allow users to receive prizes. Let's look at two probability algorithm functions first.   Algorithm one   code as follows:/**  * full probability calculation  *  * @param array $p Array (' A ' =>0.5, ' B ' =>0.2, ' C ' =>0.4) &nbsp ; * @return string returns the key  */function random ($ps) {    static $arr = Array () of the above array;     $key = MD5 ( Serialize ($ps));       if (!isset ($arr [$key])) {        $max = Array_sum ($ps);       &NB Sp foreach ($ps as $k => $v) {            $v = $v/$max * 10000             for ($i =0 $i < $v $i + +) $arr [$key] = $k;        }     {    return $arr [$key][mt_rand (0,count ($arr [$key])-1]; The     algorithm two codes are as follows: function Get_rand ($PROARR) {      $result = ';       //probability array Total probability precision     $proSum = Array_sum ($PROARR);       //probability array loop     foreach ($proArr as $k EY => $proCur) {  &NBsp       $randNum = Mt_rand (1, $proSum);          if ($randNum <= $proCur) {              $result = $key;              break;  &N Bsp      } else {              $proSum = $proCur;      &NBS P  }     }      unset ($PROARR);        return $result; } &NB Sp The above code is a classical probability algorithm, $PROARR is a pre-set array, assuming that the array is: Arrays (100,200,300,400), starting from 1,1000 this probability range to filter the first number within the range of his probability of occurrence, if not, then the probability of a null reduction , that is, the value of K minus the probability space of just that number, in this case minus 100, which means the second number is filtered in the range 1,900. In this way, there will always be a number to meet the requirements. The equivalent of going to a box to touch things, the first is not, the second is not, the third is not, the last one must be. This algorithm is simple, and very efficient, the key is that this algorithm has been used in our previous projects, especially the large amount of data in the efficiency of the project is very good. Next we configure the awards through PHP.   Code as follows: $prize _arr = Array (      ' 0 ' => array (' ID ' =>1, ' prize ' => ' tablet computer ', ' V ' =>1 '),  & nbsp   ' 1 ' => array (' ID ' =>2, ' Prize ' => ' digital camera ', ' V ' =>5),     ' 2 ' => array (' ID ' =>3, ' Prize ' => ' Speaker device ', ' V ' =>10),      ' 3 ' => array (' ID ' =>4 , ' Prize ' => ' 4G usb flash drive ', ' V ' =>12 ',      ' 4 ' => array (' ID ' =>5, ' Prize ' => ' 10Q coins ', ' V ' =>22),       ' 5 ' => array (' ID ' =>6, ' Prize ' => ' next time may be able to, ' V ' =>50), );    is a two-dimensional array, recording all the Lottery award information, where the ID of the winning rating, prize, said the prize, V to indicate the probability of winning. Note that V must be an integer, you can set the corresponding award of V to 0, meaning that the probability of the award is 0, the sum of V in the array (radix), the larger the cardinality of the probability of accuracy. In this case the sum of V is 100, then the tablet computer corresponding to the probability of winning is 1%, if the sum of V is 10000, the probability of winning is one out of 10,000. Each front-end page is requested, the PHP Loop awards are set array, and the probability calculation function Get_rand Gets the award ID drawn in. The winning prizes are saved in the array $res[' yes ', while the remaining outstanding information is kept in $res[' no ', and the JSON data is then output to the front page. The code is as follows://If the winning data is placed in the database, here it is necessary to judge the number of winners//In the 1, 2, 3 and other awards, if the maximum number of unset corresponding awards, avoid repetition of the jackpot//code here Eg:unset ($prize _arr[' 0 ') foreach ($prize _arr as $key => $val) {      $arr [$val [' id ']] = $val [' V ']; }    $rid = ge T_rand ($arr); Obtain award ID   $res [' yes '] according to probability $prize _arr[$rid -1][' Prize ']; In the awards//will be excluded from the array, the remaining awards, if the database verification, here can be saved unset ($prize _arr[$rid-1]);  Shuffle ($prize _arr); Scrambling array order for ($i =0; $i <count ($prize _arr); $i + +) {      $PR [] = $prize _arr[$i] [' Prize ']; }  $ res[' no '] = $PR;  echo json_encode ($res);     Why can't I get the jackpot?   In many similar lottery activities, participants often do not draw awards, the author from the point of view of the program to give you see, if I was the organizer of the lottery, I set up 6 awards, each award a different probability of winning, if the first prize is a senior sedan, but I set the prize probability of 0, What does that mean? This means that participants in the lottery will never get the premium sedan, no matter how they smoke it. When the organizer flips the remaining squares each time, the participants will find that the first prize may be in a number next to the square of the lottery, blaming their bad luck. Is it really a bad luck? In fact, when the participants flip the box, the program has decided the award, and Flip View the other squares see the award is only a smoke bomb, confusing the audience and participants. I want to finish reading this article, you may know that the TV show in the flop Lottery, you probably will not go to the machine election Shuangse Qiu.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.