How to resolve the algorithm Zig-zag matrix step by step in the Delphi programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Zig-zag matrix step by step in the Delphi programming language
Table of Contents
Problem Statement
Produce a zig-zag array.
A zig-zag array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you zig-zag along the array's anti-diagonals.
For a graphical representation, see JPG zigzag (JPG uses such arrays to encode images).
For example, given 5, produce this array:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Zig-zag matrix step by step in the Delphi programming language
Source code in the delphi programming language
type TMatrix = array of array of double;
procedure DisplayMatrix(Memo: TMemo; Mat: TMatrix);
{Display specified matrix}
var X,Y: integer;
var S: string;
begin
S:='';
for Y:=0 to High(Mat[0]) do
begin
S:=S+'[';
for X:=0 to High(Mat) do
S:=S+Format('%4.0f',[Mat[X,Y]]);
S:=S+']'+#$0D#$0A;
end;
Memo.Lines.Add(S);
end;
procedure ZigzagMatrix(Memo: TMemo);
var Mat: TMatrix;
var X,Y,Inx,Dir: integer;
const Size = 10;
procedure Toggle(var I: integer);
{Toggle Direction and increment I}
begin
Dir:=-Dir;
Inc(I);
end;
procedure Step(var X,Y: integer);
{Take one step "Dir" direction}
begin
X:=X+Dir;
Y:=Y-Dir;
end;
begin
SetLength(Mat,Size,Size);
Inx:=0; X:=0; Y:=0; Dir:=1;
repeat
begin
Mat[X,Y]:=Inx;
if (X+Dir)>=Size then Toggle(Y)
else if (Y-Dir)>=Size then Toggle(X)
else if (X+Dir)<0 then Toggle(Y)
else if (Y-Dir)<0 then Toggle(X)
else Step(X,Y);
Inc(Inx);
end
until Inx>=Size*Size;
DisplayMatrix(Memo,Mat);
end;
You may also check:How to resolve the algorithm Longest increasing subsequence step by step in the zkl programming language
You may also check:How to resolve the algorithm Read a file line by line step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Extreme floating point values step by step in the Pascal programming language
You may also check:How to resolve the algorithm Keyboard input/Keypress check step by step in the RPL programming language
You may also check:How to resolve the algorithm Arithmetic derivative step by step in the MiniScript programming language