根据设置的概率选择用户


Select a user according to set probability

我的数据库存储有关用户、他们的组和关系的信息。用户表中的fcount列跟踪每个用户在其当前组中拥有的关系的数量;它从0开始,并在适当的时候增加它。
我需要写一个脚本,选择所有用户在一个给定的组,然后随机选择其中一个被选中的概率是基于一个关系的数量;关系越少,概率越大。

目前,我完成了这个,减去概率部分,用下面的代码:

$query = "SELECT uid FROM users WHERE groupid=:gid AND status='1'";
...
while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
    $friends[] = $row[0];
}
foreach ($users as $value) {
    $key = array_search($value, $friends);
    unset($friends[$key]);
    shuffle($friends);
    $newrel = end($friends);
    $user = $value;
    $friends[] = $value;
    $query = "UPDATE users SET rel=:newrel WHERE uid=:uid";
    $query_params = array(':newrel' => $newrel, ':uid' => $user );
... }

我认为调整概率的最简单方法是编辑$friends数组,以便用户不止一次出现。因此,fcount为0的用户将在数组中重复5次,fcount为1的用户将重复3次。也许这不是处理它的最好方法,但它对我来说是有意义的,并且适合我已经拥有的代码。你可以提出一个更好的方案。

我还没有弄清楚的是如何取用户数组并将应该相乘的用户项相乘。

SELECT uid, fcount FROM users WHERE groupid=:gid AND status='1';

返回一个反映该表的数组:

+-----+--------+
| uid | fcount |
+-----+--------+
| 105 |      3 |
| 106 |      2 |
| 107 |      0 |
| 108 |      0 |
| 109 |      1 |
+-----+--------+

,然后变成如下数组:

array(15) { 
[0]=> string(3) "105" 
[1]=> string(3) "106" 
[2]=> string(3) "107" 
[3]=> string(3) "107" 
[4]=> string(3) "107" 
[5]=> string(3) "107" 
[6]=> string(3) "107" 
[7]=> string(3) "108" 
[8]=> string(3) "108" 
[9]=> string(3) "108" 
[10]=> string(3) "108" 
[11]=> string(3) "108"
[12]=> string(3) "109" 
[13]=> string(3) "109" 
[14]=> string(3) "109" 
}  

在我看来,这可以通过foreach来完成,它根据循环中的if语句将每个userid n次推入一个新的数组。我要试着去构建它,即使我很可能会失败。

$problist = array();
foreach ($row as $value) {
    if ($value['fcount'] == 0) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] == 1) {
        array_push($problist, $value['uid'], $value['uid'], $value['uid']);
    } elseif ($value['fcount'] >= 2) {
        $problist[] = $value['uid'];
    }
}

一般情况下最简单的概率计算方法

$relations = 10;
$chance = rand(1,100);
if ($chance <= $relations) {
// success
}

在这种情况下,关系越多,概率越大,就像如果$relations =99,你有99%的概率用relations=99命中这个用户