PHP Probabilistic algorithm function

Source: Internet
Author: User
This article mainly introduces the PHP probability algorithm function, the interest friend's reference, hoped to be helpful to everybody.

The code is as follows:

<?php/** * Probability calculation class * Can be used for sweepstakes and other */class probability{/** * probability statistics * thing = CH  ance */var $data = array ();   var $chance _count = 0;      function __construct ($initdata = Array ()) {if (!empty ($initdata)) {$this->data = $initdata;      foreach ($initdata as $d) {$this->chance_count + = $d [' num '];    }}} function AddData ($name, $chance) {$this->data[]=array (' name ' = = $name, ' num ' = $chance);  $this->chance_count + = $chance;    } function GetOne () {$index = rand (0, $this->chance_count);      foreach ($this->data as $d) {$index = $index-$d [' num '];      if ($index <=0) {return $d [' name '];  }} "return"; }}/** * Use example */$pro =new probability (), $pro->adddata (' iphone '), $pro->adddata (' Watch '); $pro->adddata ( ' $18 ', $pro->adddata (' Thank you '), $pro->adddata (' Super big ', 1); for ($i =0; $i <100; $i + +) {echo $pro- >getone (). " \ n ";} 

This is a very classical probability algorithm function:

function Get_rand ($PROARR) {   $result = ';   The total probability accuracy of the probability array   $proSum = Array_sum ($PROARR);   Probability array Loop   foreach ($proArr as $key + = $proCur) {     $randNum = Mt_rand (1, $proSum);       Extract the random number    if ($randNum <= $proCur) {       $result = $key;             The result is break      ;     } else {       $proSum-= $proCur;}   }   Unset ($PROARR);   return $result; }

Suppose: We have such an array: a prize probability 20%,b prize probability 30%,c prize probability 50%

$prize _arr =array (' A ' =>20, ' B ' =>30, ' C ' =>50);

Simulation function Execution Process:

Total probability accuracy is 20+30+50=100

First-time array loop, $procur =20

Assuming the extracted random number rand (1,100), assume that pumping to $randnum=55

If Judgment-------

If $randnum<=20, then result=a

Otherwise into the next cycle, the total probability accuracy becomes 100-20=80

Second array loop, $procur =30

Assuming the decimation of the random number rand (1,80), assume that pumping to $randnum=33

If Judgment---------

If $randnum<=30, then result=b

Otherwise into the next cycle, the total probability accuracy becomes 80-30=50

The third array loop, $prosur = 50;

Assuming the extracted random number rand (1,50), no matter how pumped, the random number will be < or = 50,

then draw result=c;

Because the sample does not change, although it is possible to extract more than one random number, the probability is constant.

Or you can do this:

  function Get_rand ($arr)  {    $pro _sum=array_sum ($arr);    $rand _num=mt_rand (1, $pro _sum);    $tmp _num=0;    foreach ($arr as $k    = + $val) {        if ($rand _num<= $val + $tmp _num)      {        $n = $k;        break;      } else      {        $tmp _num+= $val;      }    }    return $n;  }

To share with you a lottery probability algorithm

/* Classic probability algorithm, * $PROARR is a pre-set array, * Assuming array is: Array (100,200,300,400), * Start is to filter from 1,1000 this probability range of whether the first number within the probability range of his occurrence, * if not, then the probability space , that is, the value of K minus the probability space of the first number, * in this case, minus 100, that is, the second number is filtered within the 1,900 range. * This filter to the end, there will always be a number to meet the requirements. * is equivalent to go 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 data volume of the project is very efficient.  */function Get_rand ($PROARR) {$result = ';  The total probability accuracy of the probability array $proSum = Array_sum ($PROARR);    Probability array loop foreach ($proArr as $key + = $proCur) {$randNum = Mt_rand (1, $proSum);      if ($randNum <= $proCur) {$result = $key;    Break    } else {$proSum-= $proCur;  }} unset ($PROARR);  return $result;} /* * Awards Array * is a two-dimensional array that records all prize information for this draw, * where the ID indicates the winning level, prize represents the prize, and V indicates the probability of winning. * Note that the V must be an integer, and you can set the V of the corresponding prize to 0, meaning that the odds of the prize being pumped are 0, * the sum of V in the array (cardinality), the larger the cardinality, the more accurate the probability. * The sum of V in this example is 100, then the probability of winning the tablet corresponds to 1%, * if the sum of V is 10000, then the probability of winning is one out of 10,000. * */$prize _arr = Array (' 0 ' = = Array (' ID ' =>1, ' prize ' = ' tablet ', ' V ' =>1), ' 1 ' = = Array (' ID ' =>2, ' prize ' =&G t; ' Digital camera ', ' V ' =>5), ' 2 ' = = Array (' ID ' =>3, ' prize ' = ' = ' Speaker device ', ' V ' =>10), ' 3 ' = = Array (' ID ' =>4, ' prize ' = ' 4G ') ', ' V ' =>12), ' 4 ' = = Array (' ID ' =>5, ' prize ' = ' 10Q ', ' V ' =>22), ' 5 ' = = Array (' ID ' =>6, ' prize ' = ' = ' next time it will be able to be in oh ', ' V ' = &GT;50),); /* * Each front page request, PHP Loop Award set Array, * Get the prize ID from the Get_rand by the probability calculation function. * Save the winning prizes in the array $res[' yes ', * while the remaining non-winning information is saved in $res[' no ', * finally output JSON data to the front page. */foreach ($prize _arr as $key = + $val) {$arr [$val [' id ']] = $val [' V '];} $rid = Get_rand ($arr); Get the prize ID $res by probability [' yes '] = $prize _arr[$rid -1][' Prize '); Medium Prize unset ($prize _arr[$rid-1]); The prize is excluded from the array and the remaining awards are shuffle ($prize _arr); Scrambled array order for ($i =0; $i <count ($prize _arr); $i + +) {$PR [] = $prize _arr[$i] [' Prize '];} $res [' no '] = $PR;p rint_r ($res [' yes ']);

Summary : The above is the entire content of this article, I hope to be able to help you learn.

Related recommendations:

PHP (iterative + recursive) implementation of infinite level classification

Whether a mandatory parameter exists in PHP judgment function

The principle of PHP text to picture function

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.