Class: Neighbor::SparseVector
- Inherits:
-
Object
- Object
- Neighbor::SparseVector
- Defined in:
- lib/neighbor/sparse_vector.rb
Constant Summary collapse
- NO_DEFAULT =
Object.new
Instance Attribute Summary collapse
-
#dimensions ⇒ Object
readonly
Returns the value of attribute dimensions.
-
#indices ⇒ Object
readonly
Returns the value of attribute indices.
-
#values ⇒ Object
readonly
Returns the value of attribute values.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(value, dimensions = NO_DEFAULT) ⇒ SparseVector
constructor
A new instance of SparseVector.
- #to_a ⇒ Object
- #to_s ⇒ Object
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
#dimensions ⇒ Object (readonly)
Returns the value of attribute dimensions.
3 4 5 |
# File 'lib/neighbor/sparse_vector.rb', line 3 def dimensions @dimensions end |
#indices ⇒ Object (readonly)
Returns the value of attribute indices.
3 4 5 |
# File 'lib/neighbor/sparse_vector.rb', line 3 def indices @indices end |
#values ⇒ Object (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_a ⇒ Object
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_s ⇒ Object
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 |