Class: PCBR::Storage

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

Constant Summary collapse

@@default_lambda =
lambda do |a_, b_|
  raise Error.new "comparison vectors are of the different length" unless a_.size == b_.size
  tt = [0, 0, 0]
  [*a_].zip([*b_]) do |a, b|
    t = a <=> b and tt[t] = t
  end
  tt[0] + tt[1] + tt[2]
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Storage

Returns a new instance of Storage.



24
25
26
27
28
29
# File 'lib/pcbr.rb', line 24

def initialize &block
  require "set"
  @set = ::Set.new
  @table = []
  @callback = block || @@default_lambda
end

Instance Attribute Details

#setObject (readonly)

Returns the value of attribute set.



14
15
16
# File 'lib/pcbr.rb', line 14

def set
  @set
end

#tableObject (readonly)

Returns the value of attribute table.



13
14
15
# File 'lib/pcbr.rb', line 13

def table
  @table
end

Instance Method Details

#score(key) ⇒ Object



44
45
46
# File 'lib/pcbr.rb', line 44

def score key
  @table.assoc(key)[2]
end

#sortedObject



48
49
50
51
# File 'lib/pcbr.rb', line 48

def sorted
  # from the best to the worst
  @table.sort_by.with_index{ |item, i| [-item[2], i] }.map(&:first)
end

#store(key, vector = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pcbr.rb', line 31

def store key, vector = nil
  raise Error.new "duplicating key" if @set.include? key
  vector = Array key if vector.nil?
  score = 0
  @table.each do |item|
    point = @callback.call vector, item[1]
    item[2] -= point
    score += point
  end
  @set.add key
  @table.push [key, vector, score]
end