Class: WeightedSelection::Engine

Inherits:
Object
  • Object
show all
Defined in:
lib/weighted_selection/engine.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeEngine

Returns a new instance of Engine.



3
4
5
# File 'lib/weighted_selection/engine.rb', line 3

def initialize
  @items = []
end

Instance Attribute Details

#itemsObject (readonly)

Returns the value of attribute items.



41
42
43
# File 'lib/weighted_selection/engine.rb', line 41

def items
  @items
end

Instance Method Details

#add_item(item) ⇒ Object



6
7
8
# File 'lib/weighted_selection/engine.rb', line 6

def add_item(item)
  @items.push(item)
end

#add_items(items) ⇒ Object



9
10
11
# File 'lib/weighted_selection/engine.rb', line 9

def add_items(items)
  items.each { |item| add_item(item) }
end

#multiple(count) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/weighted_selection/engine.rb', line 33

def multiple(count)
  output = []
  for i in 0..count
    output.push(sample)
  end
  return output
end

#sampleObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/weighted_selection/engine.rb', line 12

def sample
  # Hold the weight sum
  sum = 0

  # Go through the items
  @items.each { |item| sum += item.weight > 0 ? item.weight : 1 }

  # Get random check-value
  check = rand(sum)

  # Loop items, again
  @items.each do |item|
    check -= item.weight
    if check <= 0
      return item
    end
  end

  # Select an item at random
  return items.sample
end