How to check if a given matrix is a sparse matrix (contains a large number of zeros) in Pascal

1 Answer

0 votes
program SparseMatrixCheck;

{$mode objfpc}

// A sparse matrix is a matrix in which the majority of elements are zero.

const
  ROW_COUNT = 3;
  COL_COUNT = 4;

type
  TMatrix = array[0..ROW_COUNT - 1, 0..COL_COUNT - 1] of Integer;

// Check if a matrix is sparse
function isSparse(rows, cols: Integer; const matrix: TMatrix): Boolean;
var
  i, j: Integer;
  zeroCount: Integer;
begin
  zeroCount := 0;

  // Count zeros
  for i := 0 to rows - 1 do
    for j := 0 to cols - 1 do
      if matrix[i][j] = 0 then
        Inc(zeroCount);

  // A matrix is sparse if more than half of its elements are zero
  Result := zeroCount > (rows * cols) div 2;
end;

var
  matrix: TMatrix = (
    (2, 0, 5, 0),
    (0, 4, 0, 0),
    (0, 8, 0, 9)
  );
  r, c: Integer;

begin
  r := ROW_COUNT;
  c := COL_COUNT;

  if isSparse(r, c, matrix) then
    WriteLn('Matrix is sparse')
  else
    WriteLn('Matrix is not sparse');
end.



(*
run:

Matrix is sparse

*)

 



answered 2 days ago by avibootz
...