From: "Jesús Gabriel y Galán" Date: 2012-11-27T02:32:41+09:00 Subject: Re: Algorithm for choosing object based on priority On Mon, Nov 26, 2012 at 6:30 PM, Jesús Gabriel y Galán wrote: > On Mon, Nov 26, 2012 at 6:10 PM, Damjan Rems wrote: >> Thanks so much. I guess I was over-complicating. > > There could be one complication depending on the requirements. If you > have to guarantee that for every N ads you show there is exactly one > time ad1, 5 times ad2, etc summing up to N. Then the best way would be > to have a hash of counts, choose a random key and reduce the count, > removing the entry if the count is 0: > > ad_count = {"ad1" => 1, "ad2" => 5, "ad3" => 3} > N = ad_count.inject(0) {|total, (k,v)| total + v} > N.times do > key = ad_count.keys[rand(ad_count.size)] > puts key > ad_count[key] -= 1 > ad_count.delete(key) if ad_count[key] <= 0 > end > > ad2 > ad2 > ad3 > ad1 > ad3 > ad3 > ad2 > ad2 > ad2 This algorithm has the consequence that the biggest weight entries appear more at the end, since each key has the same probability of being chosen. If you want weighted appearance, you should weigth the random choosing with the counts. Jesus.