class WeightedList
Constants
- VERSION
Attributes
hash[R]
random[R]
Public Class Methods
[](collection)
click to toggle source
# File lib/weighted_list.rb, line 10 def self.[](collection) new(collection) end
new(collection)
click to toggle source
# File lib/weighted_list.rb, line 14 def initialize(collection) @hash = Normalizer.call(collection.clone) end
Public Instance Methods
each(&block)
click to toggle source
# File lib/weighted_list.rb, line 18 def each(&block) hash.each_key(&block) end
sample(quantity = nil, random: Random, with_replacement: false)
click to toggle source
# File lib/weighted_list.rb, line 22 def sample(quantity = nil, random: Random, with_replacement: false) return select_item(hash, random: random).selected unless quantity quantity.times.each_with_object(initial_memo) do |_index, memo| result = select_item(memo[:current_list], random: random) return memo[:selected] if result.selected.nil? memo[:selected].push(result.selected) memo[:current_list] = (with_replacement ? hash : result.remaining) end[:selected] end
shuffle(random: Random)
click to toggle source
# File lib/weighted_list.rb, line 32 def shuffle(random: Random) sample(hash.length, random: random) end
shuffle!(random: Random)
click to toggle source
# File lib/weighted_list.rb, line 36 def shuffle!(random: Random) sample(hash.length, random: random).tap do |returned_collection| returned_collection.each_with_object({}) do |item, replace_with| replace_with[item] = hash[item] end.tap { |replace_with| @hash = replace_with } end end
Private Instance Methods
initial_memo()
click to toggle source
# File lib/weighted_list.rb, line 48 def initial_memo { selected: [], current_list: hash } end
select_item(list, random:)
click to toggle source
# File lib/weighted_list.rb, line 52 def select_item(list, random:) Sampler.new(hash: list, random: random).call end