Class: WeightedList
- Inherits:
-
Object
show all
- Includes:
- Enumerable
- Defined in:
- lib/weighted_list.rb,
lib/weighted_list/sampler.rb,
lib/weighted_list/version.rb,
lib/weighted_list/normalizer.rb
Defined Under Namespace
Classes: Normalizer, Sampler
Constant Summary
collapse
- VERSION =
'0.8.1'
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(collection) ⇒ WeightedList
Returns a new instance of WeightedList.
14
15
16
|
# File 'lib/weighted_list.rb', line 14
def initialize(collection)
@hash = Normalizer.call(collection.clone)
end
|
Class Method Details
.[](collection) ⇒ Object
10
11
12
|
# File 'lib/weighted_list.rb', line 10
def self.[](collection)
new(collection)
end
|
Instance Method Details
#each(&block) ⇒ Object
18
19
20
|
# File 'lib/weighted_list.rb', line 18
def each(&block)
hash.each_key(&block)
end
|
#sample(quantity = nil, random: Random, with_replacement: false) ⇒ Object
22
23
24
25
26
27
28
29
30
|
# 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) ⇒ Object
32
33
34
|
# File 'lib/weighted_list.rb', line 32
def shuffle(random: Random)
sample(hash.length, random: random)
end
|
#shuffle!(random: Random) ⇒ Object
36
37
38
39
40
41
42
|
# 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
|