Recently, as a result of the project needs to do a lottery application, users click the lottery, will return three different results (that is, awards: First prize, Second prize, third prize, thank you Lottery), it is clear that the probability of the prize value will be reduced in turn. This involves a similar calculation of the weight of an algorithm. According to the need to think for a long time, and finally through a simple weight calculation method to get this thing done, the probability is within the expected range.
Here is a summary of how this weight is calculated.
The first explanation is that this example is only suitable for arrays with two-dimensional arrays and one dimension is a numeric index, and the data array structure is as follows:
$data =array (
0=>array (' id ' =>1, ' name ' => ' first prize ', ' Weight ' => ' 5 '),
1=>array (' id ' =>2, ' name ' = > ' Second Prize ', ' Weight ' => '),
2=>array (' id ' =>3, ' name ' => ' third prize ', ' Weight ' => '),
3=>array ( ' id ' =>4, ' name ' => ' Thank you draw ', ' weight ' => ')
;
Here is a simple algorithm for calculating weights
The higher the weight value, the greater the probability of being returned
//author www.Alixixi.com
function countweight ($data) {
$weight =0;
$temp =array ();
foreach ($data as $v) {
$weight + = $v [' weight '];
For ($i =0 $i < $v [' weight ']; $i + +) {
$temp []= $v;//magnify Array
}
}
$int =mt_rand (0, $weight-1);// Gets a random number
$result = $temp [$int];
return $result;
}
The calculated results are returned as follows:
Array
(
[ID] => 4
[Name] => Thank you for the lottery
[Weight] => 60
)