Class: Neighbor::SparseVector

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

Constant Summary collapse

NO_DEFAULT =
Object.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, dimensions = NO_DEFAULT) ⇒ SparseVector

Returns a new instance of SparseVector.



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/neighbor/sparse_vector.rb', line 7

def initialize(value, dimensions = NO_DEFAULT)
  if value.is_a?(Hash)
    if dimensions == NO_DEFAULT
      raise ArgumentError, "missing dimensions"
    end
    from_hash(value, dimensions)
  else
    unless dimensions == NO_DEFAULT
      raise ArgumentError, "extra argument"
    end
    from_array(value)
  end
end

Instance Attribute Details

#dimensionsObject (readonly)

Returns the value of attribute dimensions.



3
4
5
# File 'lib/neighbor/sparse_vector.rb', line 3

def dimensions
  @dimensions
end

#indicesObject (readonly)

Returns the value of attribute indices.



3
4
5
# File 'lib/neighbor/sparse_vector.rb', line 3

def indices
  @indices
end

#valuesObject (readonly)

Returns the value of attribute values.



3
4
5
# File 'lib/neighbor/sparse_vector.rb', line 3

def values
  @values
end

Class Method Details

.from_text(string) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/neighbor/sparse_vector.rb', line 56

def from_text(string)
  elements, dimensions = string.split("/", 2)
  indices = []
  values = []
  elements[1..-2].split(",").each do |e|
    index, value = e.split(":", 2)
    indices << index.to_i - 1
    values << value.to_f
  end
  from_parts(dimensions.to_i, indices, values)
end

Instance Method Details

#to_aObject



25
26
27
28
29
30
31
# File 'lib/neighbor/sparse_vector.rb', line 25

def to_a
  arr = Array.new(dimensions, 0.0)
  @indices.zip(@values) do |i, v|
    arr[i] = v
  end
  arr
end

#to_sObject



21
22
23
# File 'lib/neighbor/sparse_vector.rb', line 21

def to_s
  "{#{@indices.zip(@values).map { |i, v| "#{i.to_i + 1}:#{v.to_f}" }.join(",")}}/#{@dimensions.to_i}"
end