Platinum Partner

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
{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}