Task

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:

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



Related tasks

   Spiral matrix
   Identity matrix
   Ulam spiral (for primes)


See also

   Wiktionary entry:   anti-diagonals


/* Fill a square matrix with the values 0 to N**2-1,     */
/* in a zig-zag fashion.                                 */
/* 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 matrix:');
   get list (n);
 
begin;
   declare A(n,n) fixed binary;
   declare (i, j, inc, q) fixed binary;
 
   on subrg snap begin;
      declare i fixed binary;
      do  i = 1 to n;
         put skip edit (a(i,*)) (f(4));
      end;
      stop;
   end;
 
   A = -1;
   inc = -1;
   i, j = 1;
 
loop:
   do q = 0 to n**2-1;
      a(i,j) = q;
      if q = n**2-1 then leave;
      if i = 1 & j = n then
         if iand(j,1) = 1 then /* odd-sided matrix */
            do; i = i + 1; inc = -inc; iterate loop; end;
         else  /* an even-sided matrix */
            do; i = i + inc; j = j - inc; iterate loop; end;
      if inc = -1 then if i+inc < 1 then
         do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end;
      if inc = 1 then if i+inc > n then
         do; inc = -inc; j = j + 1; a(i,j) = q; iterate loop; end;
      if inc = 1 then if j-inc < 1 then
         do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end;
      if inc = -1 then if j - inc > n then
         do; inc = -inc; i = i + 1; a(i,j) = q; iterate loop; end;
      i = i + inc; j = j - inc;
   end;
 
   /* Display the square. */
   do  i = 1 to n;
      put skip edit (a(i,*)) (f(4));
   end;
end;