Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 rows). For example, having 5 rows with weights 1,2,3,4,5 out of 1000 I'd get approximately 1/15*1000=67 times first row and so on.

The table is to be filled manually. Then I'll take a random value from it. But I want to have an ability to change the probabilities on the filling stage.

like image 462
Fluffy Avatar asked Jan 30 '26 03:01

Fluffy


1 Answers

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
like image 183
Josh Lee Avatar answered Jan 31 '26 15:01

Josh Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!