PHP抽奖算法

WBOY
WBOYOriginal
2016-06-23 13:37:361411browse

写抽奖无非就是从概率入手,每个层次的奖的概率是该权重总权重的百分比

$arr = array(
array('prize'=>'first', 'weight'=>10),
array('prize'=>'second','weight'=>10),
array('prize'=>'third', 'weight'=>80)
//权重依次排下来,权重保证为整型
);

分析上列数据。

权重加起来=100

所以只能取1到100的随机值

由于1到100的区间内值的概率都是相等的

我们可以这样处理

[1- 10]

[11-20]

[21-100]

假设用户取到随机值15

经过一等奖 发现大于一等奖的权重,15-10=5

然后经过二等奖,5小于二等奖的权重10,所以为二等奖。

这里的核心是以区间为主,从小的权重到大的权重依次遍历。而不该采取hash map浪费资源,代码如下:

    $arr = array(
array('prize'=>'first', 'weight'=>10),
array('prize'=>'second','weight'=>10),
array('prize'=>'third', 'weight'=>80)
//权重依次排下来,权重保证为整型
);
function LotteryDraw($arr){
$weightSum = 0;
foreach($arr as $rows){
$weightSum +=$rows['weight'];//总权重相加
}
$randomNumber = rand(1,$weightSum);//获得随机数
foreach($arr as $rows){
if($randomNumber return $rows['prize'];
}
else{
$randomNumber -= $rows['weight'];
}
}
}
//越多次实验越接近权重
$first = $second = $third = 0;//次数置0
for($i = 0; $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;
?>

测试的数据越大,结果越接近数学期望。即相应权重占总权重百分比。



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:5个月后换PHP工作Next article:apache加载php配置