Class: WeightedRandomSelector

Inherits:
Object
  • Object
show all
Defined in:
lib/weighted_random_selector.rb

Class Method Summary collapse

Class Method Details

.select_from_hash_list(hash_list) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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