This paper illustrates the micro-envelope algorithm implemented by PHP. Share to everyone for your reference. Specifically as follows:
Recently has been in the micro-letter group to experience the function of red envelopes, there are two types of red envelopes:
1. Ordinary Red envelopes
2. Lucky Bonus
Ordinary red envelopes need not be more analytic, pot principle, equally.
Spell Luck Red envelopes are lucky (luck), someone can rob a lot, some people rob less pitiful, of course, not first Rob must be more, after all, is random.
Think about it, write yourself to see if you can achieve similar functions (dare not to say is the algorithm).
$bonus _total Red Envelope Total amount//
$bonus _count Red envelope number
//$bonus _type red Envelope Type 1 = Lucky Bonus 0 = ordinary red envelope
function Randbonus ($bonus _ Total=0, $bonus _count=3, $bonus _type=1) {
$bonus _items = Array ();//The result to be divided
$bonus _balance = $bonus _total ; The balance after each separation
$bonus _avg = Number_format ($bonus _total/$bonus _count, 2);//The average amount of money per red envelope
$i = 0;
while ($i < $bonus _count) {
if ($i < $bonus _count-1) {
$rand = $bonus _type? Rand (1, $bonus _balance*100-1)/100): $bonus _avg; Calculate the amount of the current red envelope according to the type of red envelope
$bonus _items[] = $rand;
$bonus _balance-= $rand;
} else{
$bonus _items[] = $bonus _balance;////The last red envelope is directly contracted to all the last amount to ensure that the total amount issued is correct
}
$i + +;
return $bonus _items;
}
All right, let's take a moment to experience
Send 3 Lucky Red envelopes, the total amount is 100 Yuan
$bonus _items = Randbonus (3, 1);
View the generated red envelope
var_dump ($bonus _items);
Check the total amount is not correct, look at the micro-letter there is no pit our money
var_dump (array_sum ($bonus _items));
Another version that uses an array implementation is similar in principle:
function Sendrandbonus ($total =0, $count =3, $type =1) {
if ($type ==1) {
$input = range (0.01, $total, 0.01);
if ($count >1) {
$rand _keys = (array) array_rand ($input, $count-1);
$last = 0;
foreach ($rand _keys as $i => $key) {
$current = $input [$key]-$last;
$items [] = $current;
$last = $input [$key];
}
}
$items [] = $total-array_sum ($items);
} else{
$avg = Number_format ($total/$count, 2);
$i = 0;
while ($i < $count) {
$items [] = $i < $count-1? $avg:(-array_sum ($total));
$i + +;
}
}
return $items;
}
I hope this article will help you with your PHP program design.