PHP Probability calculation function Summary _php skill

Source: Internet
Author: User
Tags rand

Actually send this blog feeling is not what to use, too simple, will people disdain to see, will not be a person's own brain also thought of. But look at their own blog has been so long no more, really distressed ~. A rough calculation of only the code of hydrology, will occupy the OSC at least more than 10 KB of database space, but, the thought of Luantan in the egg, also relieved.

<?php/** * Probability calculation class * Can be used for lottery etc/class Probability {/** * probability statistics * thing => chance * * var $data = a
  Rray ();
 
  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 the example * * $pro =new probability ();
$pro->adddata (' iphone ', 10);
$pro->adddata (' watch ', 30);
$pro->adddata (' $18 ', 50);
$pro->adddata (' Thank you ', 10);
$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 precision of probability array 
  $proSum = Array_sum ($PROARR); 
  Probability array Loop 
  foreach ($proArr as $key => $proCur) { 
    $randNum = Mt_rand (1, $proSum);       Extract random number
    if ($randNum <= $proCur) { 
      $result = $key;             Result break
      ; 
    } else { 
      $proSum-= $proCur;           
    } 
  } Unset ($PROARR); 
  return $result; 
}

Suppose: We have such an array: a prize probability 20%,b Award probability 30%,c award 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

Suppose the sampled random number rand (1,100), assuming that the $randnum=55 is pumped

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

Suppose to extract the random number rand (1,80), assuming that the $randnum=33 is pumped

If Judgment---------

If $randnum<=30, then result=b

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

Third-time array loop, $prosur = 50;

Suppose the sampled random number rand (1,50), regardless of how it is pumped, random numbers will < or = 50,

Then come result=c;

Since the sample does not change, although more than one random number may be extracted, 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;
  }

I'm sharing a lottery probability algorithm.

* * The classical probability algorithm, * $PROARR is a predetermined 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,
 The probability space, which is the value of K minus the probability space of that number, is minus 100 in this case, which means the second number is filtered in the range 1,900.
 * This filter to the end, there will always be a number to meet the requirements.
 * It's 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 amount of data in the efficiency of the project is very good.
  * * Function Get_rand ($PROARR) {$result = ';
  The total probability precision of 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, 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 the V must be an integer, you can set the corresponding award of V to 0, which means that the probability of the award is 0, * the sum of V in the array (radix), the larger the cardinality can reflect the accuracy of the probability.
 * 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. * */$prize _arr = Array (' 0 ' => array (' ID ' =>1, ' prize ' => ' tablet computer ', ' V ' =>1 '), ' 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 currency ', ' V ' =>22 '), ' 5 ' =>
 
Array (' ID ' =>6, ' Prize ' => ' next time may be able to be in oh ', ' V ' =>50),);
 * * Each front-end page request, PHP cycle Awards set Array, * through the probability calculation function Get_rand get the award ID in the draw.
 * Save the winning prizes in the array $res[' yes '], * and the remaining outstanding information is kept in the $res[' no '], * Finally output the JSON data to the front-end page. */foreach ($prize _arr as $key => $val) {$arr [$val [' id ']] = $val [' V '];} $rid = Get_rand ($arr); To obtain the award ID $res [' yes '] = $prize _arr[$rid -1][' Prize '); Award unset ($prize _arr[$rid-1]); Remove the award from the array, leaving the award shuffle ($prize _arr);
Scrambling array order for ($i =0; $i <count ($prize _arr); $i + +) {$PR [] = $prize _arr[$i] [' Prize ']; $res [' no '] = $PR; Print_r ($res [' yes ']);

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.