按重量选择随机值php

时间:2015-12-17 17:28:30

标签: php mysql

我即将创建" lottary系统。"

看看我的桌子:

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

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

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

我在下面找到了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 colomn作为数组提取到$values,将amount colomn提取到$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

依旧等等。但我仍然坚持如何在该名单上挑选一名获胜者。

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

如果你在另一方面看到解决方案,我也会开放头脑风暴。

4 个答案:

答案 0 :(得分:2)

这不是很优雅,但适用于小型彩票。

它只是构造一个庞大的数组并随机选择一个元素。

想想一顶满是滑盖的大帽子。每个持有人获得他们在“单据”中的股份,每个持有人都标有他们的身份证。即持有者名称为“a”的十张单据,带有“b”的20张单据等等......

<?php

$holder_totals = array(
    'a' => '10',
    'b' => '20',
    'c' => '20',
    'd' => '50'
);

$big_hat = array();
foreach($holder_totals as $holder_id => $total) {
    $holder_hat = array_fill(0, intval($total), $holder_id);
    $big_hat    = array_merge($big_hat, $holder_hat);
}

// Drum roll
foreach (range(1,4) as $n) {
    $random_key = array_rand($big_hat);
    printf("Winner %d is %s.\n", $n, $big_hat[$random_key]);
    unset($big_hat[$random_key]); // Remove winning slip
}

示例输出:

Winner 1 is d.
Winner 2 is c.
Winner 3 is d.
Winner 4 is b.

大帽子看起来像这样:

Array
(
    [0] => a
    [1] => a
    [2] => a
    [3] => a
    [4] => a
    [5] => a
    [6] => a
    [7] => a
    [8] => a
    [9] => a
    [10] => b
    [11] => b
    [12] => b
    [13] => b
    [14] => b
    ... and so on...
)

答案 1 :(得分:2)

您可以只构建一个大型数组,然后从该数组中随机选择一个值,而不是按原样打印出值。

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)];

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

答案 2 :(得分:2)

rm package.zip
zip package.zip `echo config/config.json; git ls-tree --full-tree -r HEAD | awk '{print $4}'`
eb deploy

这是一个高效灵活的功能。但是如果要使用非整数加权,则必须修改它。

答案 3 :(得分:1)

您可以使用我的库nspl中的weightedChoice函数。

use function \nspl\rnd\weightedChoice;

// building your query here

$pairs = [];
while($r = $query->fetch()) {
    $pairs[] = [$r['userid'], $r['amount']];
}

$winnerId = weightedChoice($pairs);

您可以使用composer安装库:

composer require ihor/nspl

或者你可以简单地重用GitHub中的weightedChoice代码:

/**
 * Returns a random element from a non-empty sequence of items with associated weights
 *
 * @param array $weightPairs List of pairs [[item, weight], ...]
 * @return mixed
 */
function weightedChoice(array $weightPairs)
{
    if (!$weightPairs) {
        throw new \InvalidArgumentException('Weight pairs are empty');
    }

    $total = array_reduce($weightPairs, function($sum, $v) { return $sum + $v[1]; });
    $r = mt_rand(1, $total);

    reset($weightPairs);
    $acc = current($weightPairs)[1];
    while ($acc < $r && next($weightPairs)) {
        $acc += current($weightPairs)[1];
    }

    return current($weightPairs)[0];
}