<?php
$prizes[] = ['probability' => 0.1, 'total' => 1, 'name' => '一等奖'];
$prizes[] = ['probability' => 1, 'total' => 1, 'name' => '二等奖'];
$prizes[] = ['probability' => 1, 'total' => 1, 'name' => '三等奖'];
$prizes[] = ['probability' => 1, 'total' => 1,'name' => '四等奖'];
$prizes[] = ['probability' => 96.9, 'total' => 100,'name' => '谢谢参与'];
// 模拟 100 次抽奖
for ($i = 1; $i <= 1000; $i++) {
// 计算每个奖品的中奖概率区间
$probabilityRanges = [];
$totalProbability = 0;
foreach ($prizes as $prize) {
$totalProbability += $prize['probability'];
$probabilityRanges[] = $totalProbability;
}
$randomNumber = mt_rand(1, $probabilityRanges[count($probabilityRanges) - 1]);
$prizeIndex = -1;
for ($j = 0; $j < count($probabilityRanges); $j++) {
if ($randomNumber <= $probabilityRanges[$j]) {
$prizeIndex = $j;
break;
}
}
if ($prizeIndex == -1) {
echo "第 $i 次抽奖,未中奖与\n";
continue;
}
$prize = $prizes[$prizeIndex];
if ($prize['total'] == 0) {
echo "第 $i 次抽奖,未中奖与\n";
continue;
}
$prizes[$prizeIndex]['total']--;
if ($prize === false) {
echo "第 $i 次抽奖,未中奖与\n";
} else {
echo "第 $i 次抽奖,中奖:".$prize['name']."-".$prize['total']."\n";
}
};
echo 'end';
标签:奖品,php,prize,probability,抽奖,prizes,total,name From: https://www.cnblogs.com/uluu/p/17278503.html