礼品中奖概率

比如有8个礼品,中奖率0.005% - 90%,有相同的中奖率,具体计算方法看代码
如果某个礼品中奖了,则继续判断是否有相同的概率的礼品,有的话再随机选择一种礼品

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
header("Content-type:text/html;charset=utf8");
$gifts = [
['id' => 1, 'probability' => 0.005],
['id' => 2, 'probability' => 0.07],
['id' => 3, 'probability' => 0.9],
['id' => 4, 'probability' => 1],
['id' => 5, 'probability' => 10],
['id' => 6, 'probability' => 70],
['id' => 7, 'probability' => 70],
['id' => 8, 'probability' => 90],
];

$probability = 0;
$rate = 1;
$awards = array();

/**
* 1, 中奖率为0的跳过
* 2, 判断中奖率最小的是否小于1 -> true -> 获取小数位数 N,作为10的 N 次幂
* 3, 将所有中奖率转换为整数,以最小的中奖率开始
*/
foreach ($gifts as $gift) {
if (empty($gift['probability'])) continue;

if ($gift['probability'] < 1) {
$temp = explode('.', $gift['probability']);
$temp = pow(10, strlen($temp[1]));
$rate = $temp < $rate ? $rate : $temp;
}

$probability += $gift['probability'] * $rate;
$awards[] = ['id' => $gift['id'], 'probability' => $probability];
}

//echo "<pre>";print_r($awards);

/**
* 1, 如果最高中奖率小于100%,则随机数的Max值为 (100%中奖率 - 最高中奖率 ) * $rate + 最高中奖率的整数值
* 2, Max值为100%中奖率的整数值
*/
$giftCount = count($gifts);
if ($gifts[$giftCount - 1]['probability'] < 100) {
$probability += (100 - $gifts[$giftCount - 1]['probability']) * $rate;
}
$rand = mt_rand(1, $probability);

// 遍历$awards数组,当随机数小于等于某个中奖率的整数值时,则跳出
if (!empty($awards)) {
foreach ($awards as $award) {
if ($rand > 0 && $rand <= $award['probability']) {
$awardId = $award['id'];
break;
}
}
}

/**
* 1, 获取中奖ID的中奖概率
* 2, 判断是否有中奖概率相同的礼品 -> true -> 随机选取一个相同概率的礼品
*/
if (isset($awardId)) {
foreach ($gifts as $gift) {
if ($gift['id'] == $awardId) {
$awardProbability = $gift['probability'];
}
}
$tempArr = array();
foreach ($gifts as $gift) {
if ($awardProbability == $gift['probability']) {
$tempArr[] = $gift['id'];
}
}
$tempCount = count($tempArr);
if ($tempCount > 1) {
echo "Old中奖ID => " . $awardId . "<br />";
$awardId = $tempArr[mt_rand(1, $tempCount) - 1];
echo "New中奖ID => " . $awardId . "<br />";
}
}

if (isset($awardId)) {
echo "中奖ID => " . $awardId . ", 随机数 => " . $rand;
} else {
echo "未中奖, 随机数 => " . $rand;
}
0%