A simple lottery probability function

Source: Internet
Author: User

A simple lottery probability function


Absrtact: This function is mainly to determine the probability range of the random number generated ...

A simple lottery probability function:


/** *  Simple lottery probability function  *  @param  array  $rewardArray   probability, such as: $rewardArray  =  Array (10, 20, 20, 30, 10, 10), corresponding to the probability of each prize  *  @return  int      Subscript for probability array  */function luckdraw ($rewardArray) {$sum  = array_sum ($rewardArray); if ($sum  !== 100) {return  ' error:the sum of values in  $rewardArray  must  be equal to 100! ';} Get random number $rewardnum = mt_rand (0,  $sum  - 1); $totalnum  = count ($rewardArray); For ($i  = 0;  $i  <  $totalnum;  $i + +) {if ($i  == 0) {if ($rewardArray [$i]  >  $rewardNum  &&  $rewardNum  >= 0) {return  $i;}} else{$max  =  $min  = 0;for ($j  = 0;  $j  <=  $i;  $j + +) {$max  =  $max  +  $rewardArray [$j];} For ($k  = 0;  $k  <  $i;  $k + +) {$min =  $min  +  $rewardArray [$k];} if ($max  >  $rewardNum  &&  $rewardNum  >=  $min) {return  $i;}}}

This function is mainly to determine the probability range of the random number generated.


Example:


$rewardArray = Array (10, 20, 20, 30, 10, 10);//each probability corresponds to a range of values//10,:0-10//20:10-30//20:30-50//30:50-80//10:80-90// 10:90-100echo Luckdraw ($rewardArray);


A simple lottery probability 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.