55 lines
1.8 KiB
Text
55 lines
1.8 KiB
Text
/* Generates a square matrix containing the integers from 0 to N**2-1, */
|
|
/* where N is the length of one side of the square. */
|
|
/* Written 22 February 2010. */
|
|
declare n fixed binary;
|
|
|
|
put skip list ('Please type the size of the square:');
|
|
get list (n);
|
|
|
|
begin;
|
|
declare A(n,n) fixed binary;
|
|
declare (i, j, iinc, jinc, q) fixed binary;
|
|
|
|
A = -1;
|
|
|
|
i, j = 1; iinc = 0; jinc = 1;
|
|
do q = 0 to n**2-1;
|
|
if a(i,j) < 0 then
|
|
a(i,j) = q;
|
|
else
|
|
do;
|
|
/* back up */
|
|
j = j -jinc; i = i - iinc;
|
|
/* change direction */
|
|
if iinc = 0 & jinc = 1 then do; iinc = 1; jinc = 0; end;
|
|
else if iinc = 1 & jinc = 0 then do; iinc = 0; jinc = -1; end;
|
|
else if iinc = 0 & jinc = -1 then do; iinc = -1; jinc = 0; end;
|
|
else if iinc = -1 & jinc = 0 then do; iinc = 0; jinc = 1; end;
|
|
/* Take one step in the new direction */
|
|
i = i + iinc; j = j + jinc;
|
|
a(i,j) = q;
|
|
end;
|
|
if i+iinc > n | i+iinc < 1 then
|
|
do;
|
|
iinc = 0; jinc = 1;
|
|
if j+1 > n then jinc = -1; else if j-1 < 1 then jinc = 1;
|
|
if a(i+iinc,j+jinc) >= 0 then jinc = -jinc;
|
|
/* j = j + jinc; /* to move on from the present (filled) position */
|
|
end;
|
|
else i = i + iinc;
|
|
if j+jinc > n | j+jinc < 1 then
|
|
do;
|
|
jinc = 0; iinc = 1;
|
|
if i+1 > n then iinc = -1; else if i-1 < 1 then iinc = 1;
|
|
if a(i+iinc,j+jinc) >= 0 then iinc = -iinc;
|
|
i = i + iinc; /* to move on from the present (filled) position */
|
|
end;
|
|
else j = j + jinc;
|
|
end;
|
|
|
|
/* Display the square. */
|
|
do i = 1 to n;
|
|
put skip edit (A(i,*)) (F(4));
|
|
end;
|
|
|
|
end;
|