Imports System
Module RebuildSparseMatrix
' 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 full sparse matrix from compact triplet form
Function buildSparseFromCompact(compact(,) As Integer, count As Integer) As Integer(,)
Dim rowIdx(count - 1) As Integer
Dim colIdx(count - 1) As Integer
Dim values(count - 1) As Integer
For i As Integer = 0 To count - 1
rowIdx(i) = compact(0, i)
colIdx(i) = compact(1, i)
values(i) = compact(2, i)
Next
' Determine matrix dimensions automatically
Dim maxRow As Integer = 0
Dim maxCol As Integer = 0
For i As Integer = 0 To count - 1
If rowIdx(i) > maxRow Then maxRow = rowIdx(i)
If colIdx(i) > maxCol Then maxCol = colIdx(i)
Next
Dim rows As Integer = maxRow + 1
Dim cols As Integer = maxCol + 1
' Create full matrix initialized with zeros
Dim sparse(rows - 1, cols - 1) As Integer
' Fill matrix
For i As Integer = 0 To count - 1
sparse(rowIdx(i), colIdx(i)) = values(i)
Next
Return sparse
End Function
' Print a matrix
Sub printMatrix(mat(,) As Integer, title As String)
Console.WriteLine(title)
Dim rows As Integer = mat.GetLength(0)
Dim cols As Integer = mat.GetLength(1)
For i As Integer = 0 To rows - 1
For j As Integer = 0 To cols - 1
Console.Write(mat(i, j) & " ")
Next
Console.WriteLine()
Next
Console.WriteLine()
End Sub
Sub Main()
' 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
Dim compact(,) As Integer = {
{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
}
Console.WriteLine("Compact matrix:")
For i As Integer = 0 To 2
For j As Integer = 0 To 8
Console.Write(compact(i, j) & " ")
Next
Console.WriteLine()
Next
Console.WriteLine()
Dim sparse = buildSparseFromCompact(compact, 9)
printMatrix(sparse, "Sparse matrix (auto-sized):")
End Sub
End Module
' 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
'
'*/