我有一张用户地图和他们为抽奖(或彩票或其他类似活动)购买的入场券数量。
用户到条目的地图位于结构中,如下所示:
// Map the person to the amount of entries they have purchased
$entries = [
'Adam' => 5,
'James' => 3,
'Oliver' => 4,
'Holly' => 8
];我想选择一个随机的用户,但考虑到他们的机会,根据票计数。获胜的可能性必须是:
(用户票金额/票务总数)* 100 =概率百分比
例如,从测试阵列的预期结果是霍莉将赢得8次抽奖20次。
发布于 2019-12-10 13:46:11
这是一个巧合,你是问这个,因为我创造了一个方法,就这样做,就在前几天,当为一个投注网站编写脚本。
请参阅评论意见,说明守则的组成如下:
// 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;
}如果您想输出获胜项目的值(概率),请在断点返回$probability,而不是$item。
发布于 2019-12-10 13:50:40
这应该能做你想做的事情,而且很容易理解。
function rand_with_entries($entries) {
//create a temporary array
$tmp = [];
//loop through all names
foreach($entries as $name => $count) {
//for each entry for a specific name, add name to `$tmp` array
for ($x = 1; $x <= $count; $x++) {
$tmp[] = $name;
}
}
//return random name from `$tmp` array
return $tmp[array_rand($tmp)];
}发布于 2019-12-10 13:51:25
好的,您有这样的数据:
$entries = [
'Adam' => 5,
'James' => 3,
'Oliver' => 4,
'Holly' => 8
];一种方法是根据这些数据填充数组并使用array_rand。以下是一个例子:
function pickRand($array, $nb) {
$newArray = [];
foreach ($array as $name => $probability) {
$num = $probability;
while ($num > 0) {
$newArray[] = $name;
$num--;
}
}
return $newArray[array_rand($newArray, $nb)];
}并利用它:
$randomName = pickRand($entries, 1);https://stackoverflow.com/questions/59268542
复制相似问题