DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Return A Random Value By Weight In Ruby
Should be self explanatory. In the example below, "dog" will be returned 30 times as often as "parrot", and twice as often as "cat".
def rand_from_weighted_hash hash
total_weight = hash.inject(0) { |sum,(weight,v)| sum+weight }
running_weight = 0
n = rand*total_weight
hash.each do |weight,v|
return v if n > running_weight && n <= running_weight+weight
running_weight += weight
end
end
def random_pet
pet_likelihoods = {
30 => "dog",
15 => "cat",
4 => "goldfish",
1 => "parrot"
}
rand_from_weighted_hash(pet_likelihoods)
end
puts random_pet





