Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find a common element in all rows of a given matrix with sorted rows in Pascal

1 Answer

0 votes
program CommonElementMatrix;

const
  MaxRows = 4;
  MaxCols = 5;
  MaxValue = 1000;  // Assumes values are between 0 and 999

type
  TMatrix = array[1..MaxRows, 1..MaxCols] of Integer;
  TFreqMap = array[0..MaxValue] of Integer;

var
  Matrix: TMatrix;
  FreqMap: TFreqMap;
  i, j, result: Integer;

function FindCommonElementInMatrixRows(var M: TMatrix; rows, cols: Integer): Integer;
var
  i, j: Integer;
begin
  FillChar(FreqMap, SizeOf(FreqMap), 0);

  for i := 1 to rows do
  begin
    Inc(FreqMap[M[i, 1]]);
    for j := 2 to cols do
      if M[i, j] <> M[i, j - 1] then
        Inc(FreqMap[M[i, j]]);
  end;

  for i := 0 to MaxValue do
    if FreqMap[i] = rows then
    begin
      FindCommonElementInMatrixRows := i;
      Exit;
    end;

  FindCommonElementInMatrixRows := -1;
end;

begin
  // Initialize matrix 
  Matrix[1,1] := 1;  Matrix[1,2] := 2;  Matrix[1,3] := 3;  Matrix[1,4] := 5;  Matrix[1,5] := 36;
  Matrix[2,1] := 4;  Matrix[2,2] := 5;  Matrix[2,3] := 7;  Matrix[2,4] := 9;  Matrix[2,5] := 10;
  Matrix[3,1] := 5;  Matrix[3,2] := 6;  Matrix[3,3] := 8;  Matrix[3,4] := 9;  Matrix[3,5] := 18;
  Matrix[4,1] := 1;  Matrix[4,2] := 3;  Matrix[4,3] := 5;  Matrix[4,4] := 8;  Matrix[4,5] := 24;

  result := FindCommonElementInMatrixRows(Matrix, MaxRows, MaxCols);

  if result <> -1 then
    WriteLn('Common element in all rows: ', result)
  else
    WriteLn('No common element found in all rows.');
end.




(*
run:

Common element in all rows: 5

*)


 



answered Oct 3, 2025 by avibootz
...