// 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
function buildSparseFromCompact(
compact: number[][],
count: number
): number[][] {
const rowIdx: number[] = compact[0];
const colIdx: number[] = compact[1];
const values: number[] = compact[2];
// Determine matrix dimensions automatically
let maxRow: number = 0;
let maxCol: number = 0;
for (let i: number = 0; i < count; i++) {
if (rowIdx[i] > maxRow) maxRow = rowIdx[i];
if (colIdx[i] > maxCol) maxCol = colIdx[i];
}
const rows: number = maxRow + 1;
const cols: number = maxCol + 1;
// Create full matrix initialized with zeros
const sparse: number[][] = Array.from(
{ length: rows },
() => Array(cols).fill(0)
);
// Fill matrix
for (let i: number = 0; i < count; i++) {
sparse[rowIdx[i]][colIdx[i]] = values[i];
}
return sparse;
}
// Print a matrix
function printMatrix(mat: number[][], title: string): void {
console.log(title);
for (const row of mat) {
console.log(row.join(" "));
}
console.log();
}
// 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
const compact: number[][] = [
[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
];
const count = 9;
console.log("Compact matrix:");
for (let i: number = 0; i < 3; i++) {
console.log(compact[i].slice(0, count).join(" "));
}
console.log();
const sparse: number[][] = buildSparseFromCompact(compact, count);
printMatrix(sparse, "Sparse matrix (auto-sized):");
/*
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
*/