Reserving queries of random records using weights

let's say i have a model Product

There are products

id | title   | weight (integer)
1  | Sugar   | 1
2  | Salt    | 1
3  | Pepper  | 2
4  | Coke    | 5

      

So, I want to get several (say 2) random products using weights.

Product.limit(2).rand_with_weights # =>
# The probability of coke is in array is 5x times bigger than salt or sugar and 2.5x times bigger than pepper
# The probability of pepper is in array is 2x times bigger than salt or sugar
# The probability of salt or sugar in array is equal

      

How can I make this request?

+3


source to share


1 answer


According to Efraimidis & Spirakis: https://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf

If you are using postgres:

Product.order("RANDOM() ^ (1.0 / weight) DESC").limit(2)

      



proof of concept: http://sqlfiddle.com/#!17/474d2/4/0

As you can see, as expected

0


source







All Articles