This article mainly introduced the PHP implementation of the random red Packet algorithm, combined with an example of the PHP random Red Packet algorithm principle, implementation methods and related considerations, the need for friends can refer to the next
Specific as follows:
First, the overall design
There are many kinds of algorithms that you can choose from, the main "architecture" is this, using the Redis decr () command to limit the flow, using MySQL to record all the required data
Two, red envelope algorithm
For simplicity, the amount of the red envelope is expressed as an integer, assuming that each red envelope has an X sugar bean, and each person has at least one bean
The first : The maximum amount of each red envelope is: (Remaining amount/remaining red envelope number) * *, need to start the time pre-allocated to everyone a bean
function Randbean ($total _bean, $total _packet) { $min _bean = 1; $max _bean =; $range = 2; $total _bean = $total _bean-$total _packet * $min _bean; Each person reserves a minimum value $list = []; $min = 1; while (count ($list) < $total _packet) { $max = floor ($total _bean/$total _packet) * $range; $bean = rand ($min, $max); if ($bean <= $max _bean-1) { $list [] = $bean; $total _bean-= $bean; } } $list [] = $total _bean;//remaining Golden bean as the last red envelope //merge foreach ($list as $k + $v) { $list [$k] + = $min _bean; } return $list;}
Multiple statistics
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.
third , the line segment method, randomly generated several numbers, a straight line into a few paragraphs, the length of each paragraph (this fluctuation is relatively large, not very average, if the size of each red envelope is limited, it will be more troublesome)
Function ABC ($total _bean, $total _packet) { $min = 1; $max = $total _bean-1; $list = []; $maxLength = $total _packet-1; while (count ($list) < $maxLength) { $rand = Mt_rand ($min, $max); Empty ($list [$rand]) && ($list [$rand] = $rand); } $list [0] = 0; The first $list [$total _bean] = $total _bean;//Last sort ($list);//index is no longer preserved $beans = []; for ($j =1; $j <= $total _packet; $j + +) { $beans [] = $list [$j]-$list [$j-1]; } return $beans; Echo ' <pre> '; Print_r ($beans); echo Array_sum ($beans);} ABC (100000, 3);
The fourth type :
Because each person at least 1 beans, then each time the number of randomly generated beans to reserve the number of remaining * 1 beans;
After removing the number of beans that must be left, the number of the beans is randomly generated at the maximum value of the remaining number of beans.