Task

Produce a spiral array.



A   spiral array   is a square arrangement of the first    N2   natural numbers,   where the

numbers increase sequentially as you go around the edges of the array spiraling inwards.



For example, given   5,   produce this array:

 0  1  2  3  4
15 16 17 18  5
14 23 24 19  6
13 22 21 20  7
12 11 10  9  8



Related tasks

   Zig-zag matrix 
   Identity_matrix
   Ulam_spiral_(for_primes)


/* 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;