From: "Hal E. Fulton" Date: 2003-03-29T20:09:24+09:00 Subject: Re: Weighted random selection -- how would you do this? ----- Original Message ----- From: "Daniel Carrera" To: "ruby-talk ML" Sent: Saturday, March 29, 2003 12:31 AM Subject: Re: Weighted random selection -- how would you do this? > Say that you have a hash 'events' whose keys are the events you are > interested in and the values are the corresponding weights: > > e.g. > events = { > "event1" => 5, > "event2" => 17, > "event3" => 6, > "event4" => 13 > } > > Solution: > tot = 0; events.each { |event, weight| tot += weight } > val = rand tot > event = events.each do |event, weight| > val -= weight; > return event if val < 0 > end > > This should work, I think. Does indeed, thank you. The algorithm is a little non-obvious to me, but it is simpler than mine. Hal