» » Use PHP to achieve red envelopes

 

Use PHP to achieve red envelopes

Author: bamboo06 on 29-12-2015, 00:43, views: 6739

0
Use PHP to achieve distributing red envelopes, and when we enter the number and total amount, PHP will be randomly assigned to each of these two values based on the amount, to ensure that everyone can receive a red envelope, it is to ask the various amount of red envelope, all of the total amount should be equal to the total amount of red envelopes.


We first have to analyze the law.
Set the total amount of $ 10, there are N individuals randomly receive:
N = 1 First
The red envelope amount = X yuan;
N = 2 second
To ensure the normal red second issue, the first red envelope amount = a random number between 0.01 to 9.99.
Red = 10- second first red envelope amount;
N = 3 third
Red 1 = a random number between 0.01 to 9.99
Red 2 = 0.01 (10 red 1-0.01) of a random number
3 = 10- 1- red red red 2
......
So we get a rule, the amount of red in the distribution of the current, first set aside a minimum amount required for the remaining red and white, and then in the 0.01 to the total amount - between the amount set aside to take a random number, the random number is the amount of current to give a red envelope distribution.
Practical application, the program first red envelope good distribution amount, when that is made red, the number of red envelopes and the amount of each assigned well, when the user rob red, we randomly give the user returns to a red envelope.
Red Allocation Code:
$total=20;//amount  
$num=10;//Divided into 10 envelopes, 10 were randomized to receive support
$min=0.01;//Each person can receive a minimum of $0.01


for ($i=1;$i<$num;$i++) {  
    $safe_total=($total-($num-$i)*$min)/($num-$i);//Random safety limits  
    $money=mt_rand($min*100,$safe_total*100)/100;  
    $total=$total-$money; 
	$arr['res'][$i] = array(
		'i' => $i,
		'money' => $money,
		'total' => $total
	);
} 
$arr['res'][$num] = array('i'=>$num,'money'=>$total,'total'=>0);


Run the above code will output the following results:
No 1 envelope, amount: $1.39, balance: 18.61
No 2 envelope, amount: $2.1, balance: 16.51
No 3 envelope, amount: $0.27, balance: 16.24
No 4 envelope, amount: $1.83, balance: 14.41
No 5 envelope, amount: $1.33, balance: 13.08
No 6 envelope, amount: $0.73, balance: 12.35
No 7 envelope, amount: $0.58, balance: 11.77
No 8 envelope, amount: $4.26, balance: 7.51
No 9 envelope, amount: $6.15, balance: 1.36
No 10 envelope, amount: $1.36, balance: 0

Category: PHP Scripts / Javascript

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
Information
Comment on the news site is possible only within (days) days from the date of publication.