This article mainly introduces the random generation algorithm of red packets in php, which has some reference value. if you are interested, you can refer to it and think about it, write your own php version of the random generation algorithm of red packets, can you implement similar functions (not to mention the algorithm ).
// $ 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 to everyone's learning, and I hope you can support your own home.