Class: WeightedList

Inherits:
Object
  • 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.5.0'

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.keys.each(&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