Use PHP to send red envelopes, when we enter the number of red envelopes and the total amount, PHP will be based on these two values to randomly allocate each amount, to ensure that everyone can receive a red envelope, each red envelope amount of money is required to have a difference in the amount of red envelopes should be equal to the total amount
View Demo Download source code
First of all to analyze the law.
Set the total amount of 10 yuan, there are n individuals to collect randomly:
N=1 First
The red envelope amount =x yuan;
N=2 a second
To ensure that the second red envelope can be issued normally, the first red envelope amount = a random number between 0.01 and 9.99.
The second red envelope =10-the first red envelope amount;
N=3 a third.
A random number between red envelopes 1=0.01 to 9.99
A random number of red envelopes 2=0.01 to (10-red envelope 1-0.01)
Red Envelopes 3=10-Red Envelopes 1-Red Envelopes 2
......
So we get a rule, in allocating the current red envelope amount, first reserve the remaining red and white required the minimum amount, and then in 0.01 to the total amount-reserve amount between the random number, the resulting random number is the current amount of red envelopes allocated.
In practical application, the program will first allocate the amount of red envelopes, that is, when the red envelopes, the number of red envelopes and the amount of each red packets are allocated, then the user to rob red envelopes, we randomly return a red envelope to the user.
Red Envelope Allocation Code:
$total =20;//Red Envelope Total amount
$num =10;//is divided into 10 red envelopes, supports 10 people
to receive at random $min =0.01;//each person receives at least 0.01 yuan for
($i =1; $i < $num; $i + +)
{
$safe _total= ($total-($num-$i) * $min)/($num-$i);//The Random security upper bound
$money =mt_rand ($min *100, $safe _total*100) /100;
$total = $total-$money;
Echo ' $i. ' A red envelope: '. $money. ' Yuan, balance: '. $total. ' Yuan ';
}
Running the above code will output the following results:
The 1th red envelope, the amount is 2.08 yuan, the balance 17.92 yuan
The 2nd red envelope, the amount is 1.81 yuan, the balance 16.11 yuan
The 3rd red envelope, the amount is 0.15 yuan, the balance 15.96 yuan
The 4th red envelope, the amount is 1.61 yuan, the balance 14.35 yuan
The 5th Red envelope, the amount is 1.11 yuan, the balance 13.24 yuan
The 6th red envelope, the amount is 1.51 yuan, the balance 11.73 yuan
The 7th Red envelope, the amount is 1.21 yuan, the balance 10.52 yuan
The 8th red envelope, the amount is 2.58 yuan, the balance 7.94 yuan
The 9th red envelope, the amount is 5.4 yuan, the balance 2.54 yuan
The 10th red envelope, the amount is 2.54 yuan, the balance 0 yuan
The above is the use of PHP to achieve micro-letter red envelope procedures, I hope to help you, there is a need for the source of friends, you can download directly.