Random red packet generation algorithm php version, red packet algorithm php
I thought about whether I could implement similar functions by writing a random Algorithm for the php version of red packets ).
// $ Bonus_totalTotal amount of Red Packets
// $ Bonus_countNumber of Red Packets
// $ Bonus_typeRed packet type 1 = hard work red packet 0 = normal red packet
Function randBonus ($ bonus_total = 0, $ bonus_count = 3, $ bonus_type = 1) {$ bonus_items = array (); // results to be divided $ bonus_balance = $ bonus_total; // balance after each score $ bonus_avg = number_format ($ bonus_total/$ bonus_count, 2); // average money for each red packet $ 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 current red envelope amount based on the red envelope type $ bonus_items [] = $ rand; $ bonus_balance-= $ rand;} else {$ bonus_items [] = $ bonus_balance; // Contract all the final amounts for the last red packet, ensure that the total amount sent is correct} $ I ++;} return $ bonus_items ;}
Let's try it now.
// Send 3 lucky red packets, totaling $100 $ bonus_items = randBonus (100, 3, 1); // view the generated red packet var_dump ($ bonus_items ); // check whether the total amount is correct. Check if there is any trouble with var_dump (array_sum ($ bonus_items ));
Another version that uses arrays has the following principles:
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:($total-array_sum($items)); $i++; } } return $items;}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.