Class SparseVector
attr_reader :vector
def initialize(h = {})
@vector = Hash.new(0)
@vector = @vector.merge!(h)
end
def [](i)
@vector[i]
end
def to_s
@vector.to_s
end
end
class SparseMatrix
attr_reader :matrix
def initialize(h = {})
@matrix = Hash.new({})
for k in h.keys do
@matrix[k] = if h[k].is_a? SparseVector
h[k]
else
@matrix[k] = SparseVector.new(h[k])
end
end
end
def [](i)
@matrix[i]
end
def col(j)
c = {}
for r in @matrix.keys do
c[r] = @matrix[r].vector[j] if
@matrix[r].vector.keys.include? j
end
SparseVector.new c
end
end
hsh = SparseMatrix.new 1 => {1 => 33, 2 => 44, 3 => 55}, 2 => {1 => 66,
3 => 77}
puts hsh[1][3]
puts hsh.col(2)
That’s the code I have, I need to know if I can if I can get the indexes
of the hash looping through the hash.
I’ve tried using each-do, but i couldn’t make it work.
I need to do this so that I can operate with Sparse Matrices and Dense
Matrices.