小编典典

如何在MySQL表中添加“权重”并根据这些值选择随机值?

algorithm

我想创建一个表,每行包含某种权重。然后我想选择概率值等于(该行的权重)/(所有行的权重)的随机值。例如,在1000行中有5行权重为1,2,3,4,5,则第一行的权重约为1/15 * 1000 = 67倍,依此类推。

该表将手动填写。然后我从中取一个随机值。但是我希望能够在填充阶段更改概率。


阅读 634

收藏
2020-07-28

共1个答案

小编典典

我在Quod
Libet中发现了这个不错的小算法。您可能可以将其转换为一些过程SQL。

function WeightedShuffle(list of items with weights):
  max_score ← the sum of every item’s weight
  choice ← random number in the range [0, max_score)
  current ← 0
  for each item (i, weight) in items:  
    current ← current + weight  
    if current ≥ choice or i is the last item:  
      return item i
2020-07-28