Class: WeightedSelector
- Inherits:
-
Object
- Object
- WeightedSelector
- Defined in:
- lib/liquid/weighted_selector.rb
Instance Method Summary collapse
- #add(element, probability) ⇒ Object
- #delete(element) ⇒ Object
- #empty? ⇒ Boolean
- #fill_up(element) ⇒ Object
-
#initialize ⇒ WeightedSelector
constructor
A new instance of WeightedSelector.
- #pick ⇒ Object
- #pick_one ⇒ Object
- #pick_one_with_index ⇒ Object
Constructor Details
#initialize ⇒ WeightedSelector
Returns a new instance of WeightedSelector.
5 6 7 8 9 |
# File 'lib/liquid/weighted_selector.rb', line 5 def initialize @sums = [] @elements = [] @total = 0 end |
Instance Method Details
#add(element, probability) ⇒ Object
11 12 13 14 15 |
# File 'lib/liquid/weighted_selector.rb', line 11 def add(element, probability) @elements << element @total += probability @sums << @total end |
#delete(element) ⇒ Object
17 18 19 20 21 22 23 24 |
# File 'lib/liquid/weighted_selector.rb', line 17 def delete(element) idx = @elements.index(element) if idx @total -= @sums[idx] @sums.delete_at(idx) @elements.delete_at(idx) end end |
#empty? ⇒ Boolean
30 31 32 |
# File 'lib/liquid/weighted_selector.rb', line 30 def empty? @elements.empty? end |
#fill_up(element) ⇒ Object
26 27 28 |
# File 'lib/liquid/weighted_selector.rb', line 26 def fill_up(element) add(element, 1 - @total) if @total < 1 end |
#pick ⇒ Object
45 46 47 |
# File 'lib/liquid/weighted_selector.rb', line 45 def pick pick_one end |
#pick_one ⇒ Object
41 42 43 |
# File 'lib/liquid/weighted_selector.rb', line 41 def pick_one pick_one_with_index[0] unless empty? end |
#pick_one_with_index ⇒ Object
35 36 37 38 39 |
# File 'lib/liquid/weighted_selector.rb', line 35 def pick_one_with_index rnd = Kernel.rand * @total idx = @sums.index { |x| x >= rnd } [@elements[idx], idx] end |