gpt4 book ai didi

php - 基于概率从PHP数组中选择随机项目

转载 作者:行者123 更新时间:2023-12-04 21:18:51 24 4
gpt4 key购买 nike

我有一张用户 map 以及他们为抽奖(或彩票或任何其他类似事件)购买的条目/门票数量。

用户到条目的映射结构如下所示:

// Map the person to the amount of entries they have purchased
$entries = [
'Adam' => 5,
'James' => 3,
'Oliver' => 4,
'Holly' => 8
];

我想选择一个随机用户,但根据票数考虑他们的机会。获胜的概率必须是:

(User Ticket Amount / Total Ticket Count) * 100 = Probability percentage



例如,从测试数组来看,预期结果是 Holly 将赢得 20 次抽奖中的 8 次。

最佳答案

前几天为博彩网站编写脚本时,我创建了一种方法来执行此操作,因此您会问这个问题是巧合。

请参阅注释以解释代码的组成:

// The array passed to the function should be your $entries array
function randProb(array $items) {
$totalProbability = 0; // This is defined to keep track of the total amount of entries

foreach ($items as $item => $probability) {
$totalProbability += $probability;
}

$stopAt = rand(0, $totalProbability); // This picks a random entry to select
$currentProbability = 0; // The current entry count, when this reaches $stopAt the winner is chosen

foreach ($items as $item => $probability) { // Go through each possible item
$currentProbability += $probability; // Add the probability to our $currentProbability tracker
if ($currentProbability >= $stopAt) { // When we reach the $stopAt variable, we have found our winner
return $item;
}
}

return null;
}

有任何问题欢迎在下方提问,如果您想输出中奖元素的值(value)(概率),返回 $probability在断点而不是 $item

关于php - 基于概率从PHP数组中选择随机项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59268542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com