Ask the great God for guidance????
Demand for a lottery:
First Prize 1000, second prize 300,000, third prize 300,000. How to quickly randomly throw a prize? I used the array, put the prizes in the array, and then randomly throw one, this way feel a bit slow, it takes 1-2 seconds to get a prize. Is there any other way to seek the guidance of the great God?
------to solve the idea----------------------
Test example
$ar = Array (1 +, 2 = 300000, 3 = 300000); Prize pool
while (Array_sum ($ar)) {
$n = Get_rand ($ar); Get the prize level and print it out to see the distribution
@ $res [$n]++;
}
Print_r ($res);//See the winning distribution
Print_r ($ar); See if the prize pool has any remaining
Function Get_rand (& $PROARR) {
$proSum = Array_sum ($PROARR);
$randNum = Mt_rand (1, $proSum);
foreach ($proArr as $key = = $proCur) {
$proSum-= $proCur;
if ($randNum > $proSum) {
$PROARR [$key]--; Deducted from the prize pool.
return $key;
}
}
}
Array
(
[2] = 300000
[3] = 300000
[1] = 1000
)
Array
(
[1] = 0
[2] = 0
[3] = 0
)
When practical, you will need to save the change of the prize pool for the next draw to be used
------to solve the idea----------------------
If it was me ... Put the user or draw into the database, add a field after the "winning state", 0 = no, 1= First prize ...
Each time you use the SQL random statement to extract a winning status of 0 users, and then update to
------to solve the idea----------------------
If it's a probability lottery,
$ar = Array (1 =, 2 =, 3 = 60); Probability of winning
for ($i =0; $i <10000; $i + +) {//Draw 10,000 times
$n = Get_rand ($ar); Get the prize level and print it out to see the distribution
@ $res [$n]++;
}
Print_r ($res);//See the winning distribution
Function Get_rand (& $PROARR) {
$proSum = Array_sum ($PROARR);
$randNum = Mt_rand (1, $proSum);
foreach ($proArr as $key = = $proCur) {
$proSum-= $proCur;
if ($randNum > $proSum) {
$PROARR [$key]--; Deducted from the prize pool because it is a probability lottery, this sentence will not be
return $key;
}
}
}
Possible results
Array
(
[3] = 5955
[2] = 3059
[1] = 986
)