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

1 Answer

0 votes
program RebuildSparseMatrix;

{$mode objfpc}

type
  TCompact = array[0..2, 0..8] of Integer;
  TSparseRow = array of Integer;
  TSparse = array of TSparseRow;

// 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(const compact: TCompact;
                                count: Integer;
                                out rows, cols: Integer): TSparse;
var
  i: Integer;
  maxRow, maxCol: Integer;
  sparse: TSparse;
begin
  // Determine matrix dimensions automatically
  maxRow := 0;
  maxCol := 0;

  for i := 0 to count - 1 do
  begin
    if compact[0, i] > maxRow then
      maxRow := compact[0, i];
    if compact[1, i] > maxCol then
      maxCol := compact[1, i];
  end;

  rows := maxRow + 1;
  cols := maxCol + 1;

  // Create full matrix initialized with zeros
  SetLength(sparse, rows);
  for i := 0 to rows - 1 do
    SetLength(sparse[i], cols);

  // Fill matrix
  for i := 0 to count - 1 do
    sparse[compact[0, i]][compact[1, i]] := compact[2, i];

  Result := sparse;
end;

// Print a matrix
procedure printMatrix(const mat: TSparse; rows, cols: Integer; const title: String);
var
  i, j: Integer;
begin
  WriteLn(title);
  for i := 0 to rows - 1 do
  begin
    for j := 0 to cols - 1 do
      Write(mat[i][j], ' ');
    WriteLn;
  end;
  WriteLn;
end;

var
  compact: TCompact;
  sparse: TSparse;
  rows, cols: Integer;
  i, j: Integer;

begin
  // 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] := 0; compact[0,1] := 0; compact[0,2] := 1; compact[0,3] := 1;
  compact[0,4] := 1; compact[0,5] := 3; compact[0,6] := 3; compact[0,7] := 3;
  compact[0,8] := 4;

  compact[1,0] := 2; compact[1,1] := 4; compact[1,2] := 2; compact[1,3] := 3;
  compact[1,4] := 6; compact[1,5] := 1; compact[1,6] := 2; compact[1,7] := 5;
  compact[1,8] := 4;

  compact[2,0] := 3; compact[2,1] := 8; compact[2,2] := 5; compact[2,3] := 7;
  compact[2,4] := 1; compact[2,5] := 2; compact[2,6] := 6; compact[2,7] := 4;
  compact[2,8] := 9;

  WriteLn('Compact matrix:');
  for i := 0 to 2 do
  begin
    for j := 0 to 8 do
      Write(compact[i, j], ' ');
    WriteLn;
  end;
  WriteLn;

  sparse := buildSparseFromCompact(compact, 9, rows, cols);

  printMatrix(sparse, rows, cols, 'Sparse matrix (auto-sized):');
end.



(*
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

*)

 



answered 1 day ago by avibootz

Related questions

...