An implementation of red envelope algorithm (PHP)

Source: Internet
Author: User

Some time ago there is a project need to use the red envelope algorithm, this thought is simple, fine thinking under a bit complex. So Baidu a bit, did not expect to find out a lot, some of the writing is very complex. Because of the time is a little tight, I found a simple point. Then refer to write one. The reference address is: 52954413;

The red envelopes in this address are written in Java. Based on the principle, I wrote it over PHP and improved the point. His algorithm does not add the maximum minimum limit for each red envelope. I added it when I wrote it in PHP. The code is as follows:

<?php/* $total _money: Total amount of red envelopes $total_people: Total people/overall number $min_money: The minimum amount of each red envelope $max_money: The maximum amount of each red envelope */function  Redpack ($total _money, $total _people, $min _money, $max _money) {    $ret =array ();    $ New_ret=array ();       $total _real_money= $total _money-$total _people* $min _money;     $ret [0]=0;   for ($i =1; $i < $total _people; $i + +) {              $ret [$i]=get_rand ($ret [$i-1], $total _real_money, ($max _money-$ Min_money));               } sort ($ RET), for ($j =0; $j <count ($ret), $j + +) {if ($j ==count ($ret)-1) {$new _ret[count ($ret) -1]= $total _real_money-$ret [ Count ($ret) -1]+ $min _money;} else{     $new _ret[]= $ret [$j +1]-$ret [$j]+ $min _money;}} Shuffle ($new _ret);  return  $new _ret;} Function get_rand ($start, $end, $max) {     $tmp =rand ($start, $end);      $total _max= $start + $max         if ($tmp > ($total _max)  | |  empty ($tmp)) {        return get_rand ($start, $end, $max);     }else{        return  $tmp;     }    }


An implementation of red envelope algorithm (PHP)

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.