Writing a lottery is nothing more than probability, each level of the probability of the prize is the weight of the total weight of the percentage
$arr = Array (
Array (' prize ' = ' first ', ' Weight ' =>10),
Array (' prize ' = ' second ', ' Weight ' =>10),
Array (' prize ' = ' third ', ' Weight ' =>80)
Weights are ranked in turn, and the weights are guaranteed to be integer
);
Analyze the above data.
Weights add up =100
So we can only take random values from 1 to 100.
Because the probabilities of values in the range 1 to 100 are equal
We can handle this.
[1-10]
[11-20]
[21-100]
Suppose the user takes a random value of 15
After the first prize found more than the first prize weight, 15-10=5
Then after the second prize, 5 is less than the second prize of the weight 10, so for the second prize.
The core here is to interval-based, from small weights to large weights in turn. Instead of taking a hash map to waste resources, the code is as follows:
<?php
$arr = Array (
Array (' prize ' = ' first ', ' Weight ' =>10),
Array (' prize ' = ' second ', ' Weight ' =>10),
Array (' prize ' = ' third ', ' Weight ' =>80)
Weights are ranked in turn, and the weights are guaranteed to be integer
);
function Lotterydraw ($arr) {
$weightSum = 0;
foreach ($arr as $rows) {
$weightSum + = $rows [' Weight '];//total weight added
}
$randomNumber = rand (1, $weightSum);//Get random numbers
foreach ($arr as $rows) {
if ($randomNumber <= $rows [' weight ']) {
return $rows [' Prize '];
}
else{
$randomNumber-= $rows [' Weight '];
}
}
}
The more experiments you get, the closer the weight
$first = $second = $third = 0;//number of times 0
for ($i = 0; $i <100000; $i + +) {
$res = Lotterydraw ($arr);
if ($res = = "First") {
$first + +;
}else if ($res = = "Second") {
$second + +;
}else{
$third + +;
}
}
echo "first=". Floatval ($first)/100000;
echo "echo "second=". Floatval ($second)/100000;
echo "echo "third=". Floatval ($third)/100000;
?>
The larger the data is tested, the closer the result is to the mathematical expectation. That is, the corresponding weight is the total weight percentage.
PHP Lottery algorithm