From: Daniel Carrera Date: 2003-03-29T15:31:14+09:00 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. On Sat, Mar 29, 2003 at 03:11:58PM +0900, Hal E. Fulton wrote: > Here's a little question for you. > > Given: A set of items, each with > an associated integer representing > the relative likelihood that each > item will be selected. > > Write: A method that will select > a random item. > > I've started this a couple of times, > but have become convinced I'm making > it too hard, and someone can probably > come up with a three-liner. > > Any ideas? > > Cheers, > Hal > > -- Daniel Carrera Graduate Teaching Assistant. Math Dept. University of Maryland. (301) 405-5137 -- distrain: distrain (di-STRAYN) verb tr., intr. To seize the property in order to force payment for damages, debt, etc.