从成千上万的用户中选择可能有数百张票的抽奖券

时间:2014-03-31 14:03:20

标签: php mysql sql

我正在创建一个抽奖活动,目前有一个包含用户名和分配给他们的门票数量的数据库。唯一公平的方式我可以想到公平地选择胜利者,即你拥有的门票越多,获胜的几率就越高;是通过创建一个单独的表,其中列出的用户名称乘以他们拥有的票证数量并随机选择一个。这将创建一个庞大的数据库。选择获胜者的最佳方式是什么?最好是通过PHP。

编辑*用户获得票证,即+1票'票。门票实际上没有分配任何东西,使它们与其他门票不同。

用户名门票 Tinman 55

提前谢谢。

2 个答案:

答案 0 :(得分:0)

你只需要一张用户和抽奖券号码表......

John  108
John  109
John  110
Paul  111
约翰的获胜机会是保罗的3倍。

答案 1 :(得分:0)

您可以使用此功能:

/**
* getRandomWeightedElement()
* Utility function for getting random values with weighting.
* Pass in an associative array, such as array('A'=>5, 'B'=>45, 'C'=>50)
* An array like this means that "A" has a 5% chance of being selected, "B" 45%, and "C" 50%.
* The return value is the array key, A, B, or C in this case.  Note that the values assigned
* do not have to be percentages.  The values are simply relative to each other.  If one value
* weight was 2, and the other weight of 1, the value with the weight of 2 has about a 66%
* chance of being selected.  Also note that weights should be integers.
* 
* @param array $weightedValues
*/
function getRandomWeightedElement(array $weightedValues) {
  $rand = mt_rand(1, (int) array_sum($weightedValues));

  foreach ($weightedValues as $key => $value) {
    $rand -= $value;
    if ($rand <= 0) {
      return $key;
    }
  }
}

来源:https://stackoverflow.com/a/11872928/3449528