How to reconstruct a full sparse matrix from a compact (triplet) matrix in Ruby

1 Answer

0 votes
# A sparse matrix is a matrix in which the majority of elements are zero.

# To rebuild a sparse matrix from a compact (triplet) representation,
# We create a full matrix initialized with zeros, then place each
# non‑zero element at its (row, column) position.

# Build a full sparse matrix from compact triplet form
def build_sparse_from_compact(compact, count)
  row_idx = compact[0]
  col_idx = compact[1]
  values  = compact[2]

  # Determine matrix dimensions automatically
  max_row = 0
  max_col = 0

  count.times do |i|
    max_row = row_idx[i] if row_idx[i] > max_row
    max_col = col_idx[i] if col_idx[i] > max_col
  end

  rows = max_row + 1
  cols = max_col + 1

  # Create full matrix initialized with zeros
  sparse = Array.new(rows) { Array.new(cols, 0) }

  # Fill matrix
  count.times do |i|
    sparse[row_idx[i]][col_idx[i]] = values[i]
  end

  sparse
end

# Print a matrix
def print_matrix(mat, title)
  puts title
  mat.each do |row|
    puts row.join(" ")
  end
  puts
end

# Compact matrix:
# 0 0 1 1 1 3 3 3 4
# 2 4 2 3 6 1 2 5 4
# 3 8 5 7 1 2 6 4 9

compact = [
  [0, 0, 1, 1, 1, 3, 3, 3, 4],  # row indices
  [2, 4, 2, 3, 6, 1, 2, 5, 4],  # column indices
  [3, 8, 5, 7, 1, 2, 6, 4, 9]   # values
]

count = 9

puts "Compact matrix:"
3.times do |i|
  puts compact[i][0...count].join(" ")
end
puts

sparse = build_sparse_from_compact(compact, count)

print_matrix(sparse, "Sparse matrix (auto-sized):")



=begin
run:

Compact matrix:
0 0 1 1 1 3 3 3 4
2 4 2 3 6 1 2 5 4
3 8 5 7 1 2 6 4 9

Sparse matrix (auto-sized):
0 0 3 0 8 0 0
0 0 5 7 0 0 1
0 0 0 0 0 0 0
0 2 6 0 0 4 0
0 0 0 0 9 0 0

=end

 



answered 2 hours ago by avibootz

Related questions

...