class WeightedList::Sampler
Constants
- Result
Attributes
hash[R]
random[R]
Public Class Methods
new(hash:, random:)
click to toggle source
# File lib/weighted_list/sampler.rb, line 5 def initialize(hash:, random:) @hash = hash @random = random end
Public Instance Methods
call()
click to toggle source
# File lib/weighted_list/sampler.rb, line 10 def call Result.new(selected, remaining) end
Private Instance Methods
remaining()
click to toggle source
# File lib/weighted_list/sampler.rb, line 34 def remaining hash.reject { |item, _weight| selected == item } end
select()
click to toggle source
# File lib/weighted_list/sampler.rb, line 20 def select return if hash.empty? current_target = random.rand(total_weight) hash.each do |item, weight| return item if current_target <= weight current_target -= weight end end
selected()
click to toggle source
# File lib/weighted_list/sampler.rb, line 30 def selected @selected ||= select end
total_weight()
click to toggle source
# File lib/weighted_list/sampler.rb, line 38 def total_weight @total_weight ||= hash.values.reduce(&:+) end