gpt4 book ai didi

php - 按权重选择随机值php

转载 作者:可可西里 更新时间:2023-11-01 07:22:06 28 4
gpt4 key购买 nike

我要创建“彩票系统”。

看看我的 table :

userid-lottaryid-amount
1 -------- 1 ---- 1
2 -------- 1 ---- 10
3 -------- 1 ---- 15
4 -------- 1 ---- 20

我想选出一个获胜者。另一个人获得第二名。

我无法随机选择获胜者,因为第 4 位用户有 20 张票,而第 1 位用户只有一张。所以我需要按权重生成随机结果,以便更公平。

我在下面找到了 php 函数,但不知道如何使用它。

      function weighted_random_simple($values, $weights){ 
$count = count($values);
$i = 0;
$n = 0;
$num = mt_rand(0, array_sum($weights));

while($i < $count){
$n += $weights[$i];
if($n >= $num){
break;
}
$i++;
}
return $values[$i];

}

$values = array('1', '10', '20', '100');
$weights = array(1, 10, 20, 100);

echo weighted_random_simple($values, $weights);

我必须将 userid 列作为数组获取到 $values 并将 amount 列获取到 $weights。但我做不到。

到目前为止,这是我的代码:

    $query = $handler->prepare("SELECT 

`cvu`.`lottaryid` as `lottaryid`,
`cvu`.`userid` as `userid`,
`cvu`.`amount` as `amount`,

`members`.`id` as `members_memberid`,
`members`.`username` as `username`

FROM `lottariesandmembers` as `cvu`

LEFT JOIN `members` as `members` ON `cvu`.`userid` = `members`.`id` WHERE `cvu`.`lottaryid` = 2");
$query->bindParam(':lottaryid', $lottaryid, PDO::PARAM_INT);
$query->execute();



while($r = $query->fetch()) {

for ( $count=1 ; $count <= $r["amount"] ; $count++ ) {

$abcprint = "$r[userid].$count - $r[username] - <br>";

echo "$abcprint";

}


}

我的这段代码只列出了用户数量的次数。例如:

1.1 user1
2.1 user2
2.2 user2
2.3 user2
..
2.10 user2
3.1 user3
..
3.15 user3
4.1 user4
..
4.20 user4

等等……但我不知道如何从该列表中选出获胜者。

如果你愿意帮助我,我想合并这些代码并创建这个小脚本。

如果您看到相反的解决方案,我也愿意集思广益。

最佳答案

您可以构建一个大数组,然后从该数组中随机选择一个值,而不是打印出您正在执行的值。

while($r = $query->fetch()) {
for ( $i=0; $i <= $r["amount"]; $i++ ) {
// Add the user into the array as many times as they have tickets
$tickets[] = $r['userid'];
}
}

// select the first place winner
$first = $tickets[mt_rand(0, count($tickets) - 1)];

// remove the first place winner from the array
$tickets = array_values(array_filter($tickets, function($x) use ($first) {
return $x != $first;
}));

// select the second place winner
$second = $tickets[mt_rand(0, count($tickets) - 1)];

我确信有一种更有效的方法可以使用数学来做到这一点,但我需要多考虑一下......

关于php - 按权重选择随机值php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34340724/

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