Class: WeightedPicker::Tree

Inherits:
Object
  • Object
show all
Defined in:
lib/weightedpicker/tree.rb

Defined Under Namespace

Classes: NoEntryError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Tree

Returns a new instance of Tree.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/weightedpicker/tree.rb', line 14

def initialize(data)
  @size = data.size #for return hash.

  @names = data.keys
  @weights = []
  @weights[0] = data.values

  #Fill 0 to 2**n
  @size.upto ((2 ** depth) - 1) do |i|
    @weights[0][i] = 0
  end

  depth.times do |i|
    @weights[i+1] = []
    num = @weights[i].size
    (num - num / 2).times do |j|
      @weights[i+1] << @weights[i][2*j] + @weights[i][2*j + 1]
    end
  end

  @weights.reverse!
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



9
10
11
# File 'lib/weightedpicker/tree.rb', line 9

def size
  @size
end

Instance Method Details

#lighten(item) ⇒ Object

Raises:



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/weightedpicker/tree.rb', line 73

def lighten(item)
  raise NoEntryError unless @names.include?(item)
  id = index(item)
  old_weight = @weights[-1][id]
  if (old_weight / 2 < WeightedPicker::MIN_WEIGHT)
    add_weight = 0
  else
    add_weight = - old_weight / 2
  end
  return if add_weight == 0
  add_ancestors(id, add_weight)
end

#names_weightsObject

Return internal data as a Hash.



38
39
40
41
42
43
44
# File 'lib/weightedpicker/tree.rb', line 38

def names_weights
  results = {}
  @size.times do |i|
    results[@names[i]] = @weights[-1][i]
  end
  results
end

#pickObject

Raises:



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/weightedpicker/tree.rb', line 46

def pick
  raise NoEntryError if @weights[0][0] == 0

  current_index = 0
  depth.times do |i|
    next_id0 = 2 * current_index
    next_id1 = 2 * current_index + 1
    #puts
    choise = choose( @weights[i+1][next_id0], @weights[i+1][next_id1])
    current_index = 2 * current_index + choise
  end
  return @names[current_index]
end

#weigh(item) ⇒ Object

Raises:



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/weightedpicker/tree.rb', line 60

def weigh(item)
  raise NoEntryError unless @names.include?(item)
  id = index(item)
  old_weight = @weights[-1][id]
  if (WeightedPicker::MAX_WEIGHT < old_weight * 2)
    add_weight = WeightedPicker::MAX_WEIGHT - old_weight
  else
    add_weight = old_weight
  end
  return if add_weight == 0
  add_ancestors(id, add_weight)
end