January 14, 2017 14:19:14 Saturday
For simplicity, use integers, assuming that each red envelope has an X of sugar beans
A: Defense, the maximum amount of each red envelope is: (the remaining amount/remaining red envelopes number)
1 functionRandbean ($total _bean,$total _packet)2 {3 $CP _total_bean=$total _bean;4 $CP _total_packet=$total _packet;5 6 $arr= [];7 $min= 1;8 while($total _packet> 1){9 $max= Floor($total _bean/$total _packet) * 2;Ten $bean=Rand($min,$max); One A $arr[] =$bean; - - $total _bean-=$bean; the $total _packet--; - } - - $arr[] =$total _bean;//the remaining beans as the last red envelope + if($total _bean= = 0) {//Prevent the last red envelope amount to be 0, recursive, 100,000 times in the case of about 1000 occurrences - returnRandbean ($CP _total_bean,$CP _total_packet); +}Else { A return $arr; at } -}
The second, to its simple extension, the maximum amount of each red envelope is: (the remaining amount/remaining red envelopes number); But ask for a minimum of 2 red envelopes at a time.
PHP random Red Envelope algorithm