How to add “weights” to a MySQL table and select random values according to these?

后端 未结 6 685
粉色の甜心
粉色の甜心 2021-01-03 10:22

I want to create a table, with each row containing some sort of weight. Then I want to select random values with the probability equal to (weight of that row)/(weight of all

6条回答
  •  春和景丽
    2021-01-03 11:03

    I found this nice little algorithm in Quod Libet. You could probably translate it to some procedural 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
    

提交回复
热议问题