class WeightedRandomSelector

Public Class Methods

select_from_hash_list(hash_list) click to toggle source
# File lib/weighted_random_selector.rb, line 3
def self.select_from_hash_list(hash_list)

  # Calculate the sum of the weights
  weighted_sum = hash_list.map{|k,v| v}.reduce(:+)
  random_num = 1 + rand(weighted_sum)

  # Imagine random_num is a number between 1 and the sum of the weights.
  # This range is partitioned to identify each hash key.

  # Ex: If the key A has a weight of 4 and B has a weight of 10
  # Weighted sum will be 14. If the random number is 1-4 then A will be selected
  # If the random number is 5-14 then B will be selected
  
  counter = 0
  hash_list.each do |k,v|
    counter += v
    return k if counter >= random_num
  end
  raise "Something went wrong with this gem."
end