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,927 questions

51,860 answers

573 users

How to convert a matrix of numbers to a string in Pascal

1 Answer

0 votes
program ConvertMatrixToString;

uses 
  SysUtils; // IntToStr // Format // Trim

const
  Rows = 5;
  Cols = 6;

type
  TMatrix = array[1..Rows, 1..Cols] of Integer;
  TSizeArray = array[1..Cols] of Integer;

function RowToString(Row: array of Integer; SizesArr: TSizeArray): String;
var
  i: Integer;
  StrVal: String;
begin
  RowToString := '';
  for i := 0 to High(Row) do
  begin
    StrVal := IntToStr(Row[i]);
    RowToString := RowToString + Format('%-' + IntToStr(SizesArr[i + 1]) + 's', [StrVal]) + ' ';
  end;
end;

function ConvertMatrixToString(Matrix: TMatrix): String;
var
  SizesArr: TSizeArray;
  i, j: Integer;
  TempRow: array of Integer;
begin
  // Initialize column size tracking
  for j := 1 to Cols do
    SizesArr[j] := 0;

  // Find max width of each column
  for i := 1 to Rows do
    for j := 1 to Cols do
    begin
      if Length(IntToStr(Matrix[i, j])) > SizesArr[j] then
        SizesArr[j] := Length(IntToStr(Matrix[i, j]));
    end;

  // Convert matrix to formatted string
  ConvertMatrixToString := '';
  for i := 1 to Rows do
  begin
    SetLength(TempRow, Cols);
    for j := 1 to Cols do
      TempRow[j - 1] := Matrix[i, j];

    ConvertMatrixToString := ConvertMatrixToString + RowToString(TempRow, SizesArr) + LineEnding;
  end;
  
  ConvertMatrixToString := Trim(ConvertMatrixToString);
end;

var
  Matrix: TMatrix = (
    (4, 7, 9, 18, 29, 0),
    (1, 9, 18, 99, 4, 3),
    (9, 17, 89, 2, 7, 5),
    (19, 49, 6, 1, 9, 8),
    (29, 4, 7, 9, 18, 6)
  );

begin
  WriteLn(ConvertMatrixToString(Matrix));
end.



  
(*
run:

4  7  9  18 29 0 
1  9  18 99 4  3 
9  17 89 2  7  5 
19 49 6  1  9  8 
29 4  7  9  18 6
  
*)  

 



answered May 24, 2025 by avibootz
...