How to count the number of sorted rows in either increasing or decreasing order in a matrix using Pascal

1 Answer

0 votes
program SortedRows;

const
  ROWS = 4;
  COLS = 5;

type
  Matrix = array[1..ROWS, 1..COLS] of Integer;

function SortedCount(mat: Matrix; rows, cols: Integer): Integer;
var
  result, i, j: Integer;
begin
  result := 0;

  // Check for strictly increasing rows
  for i := 1 to rows do
  begin
    j := 1;
    while (j < cols) and (mat[i, j + 1] > mat[i, j]) do
      Inc(j);
    if j = cols then
      Inc(result);
  end;

  // Check for strictly decreasing rows
  for i := 1 to rows do
  begin
    j := cols;
    while (j > 1) and (mat[i, j - 1] > mat[i, j]) do
      Dec(j);
    if (cols > 1) and (j = 1) then
      Inc(result);
  end;

  SortedCount := result;
end;

var
  mat: Matrix;
begin
  // Initialize the matrix
  mat[1,1] := 1;  mat[1,2] := 2;  mat[1,3] := 3;  mat[1,4] := 4;  mat[1,5] := 5;
  mat[2,1] := 2;  mat[2,2] := 3;  mat[2,3] := 1;  mat[2,4] := 8;  mat[2,5] := 7;
  mat[3,1] := 8;  mat[3,2] := 7;  mat[3,3] := 6;  mat[3,4] := 5;  mat[3,5] := 4;
  mat[4,1] := 5;  mat[4,2] := 7;  mat[4,3] := 8;  mat[4,4] := 9;  mat[4,5] := 10;

  WriteLn('Number of sorted rows: ', SortedCount(mat, ROWS, COLS));
end.



(*
run:

Number of sorted rows: 3

*)

 



answered Oct 1 by avibootz
...