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)