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


MODULE ZigZag EXPORTS Main;
 
IMPORT IO, Fmt;
 
TYPE Matrix = REF ARRAY OF ARRAY OF CARDINAL;
 
PROCEDURE Create(size: CARDINAL): Matrix =
  PROCEDURE move(VAR i, j: INTEGER) =
    BEGIN
      IF j < (size - 1) THEN
        IF (i - 1) < 0 THEN
          i := 0;
        ELSE
          i := i - 1;
        END;
        INC(j);
      ELSE
        INC(i);
      END;
    END move;
 
  VAR data := NEW(Matrix, size, size);
      x, y: INTEGER := 0;
  BEGIN
    FOR v := 0 TO size * size - 1 DO
      data[y, x] := v;
      IF (x + y) MOD 2 = 0 THEN
        move(y, x);
      ELSE
        move(x, y);
      END;
    END;
    RETURN data;
  END Create;
 
PROCEDURE Print(data: Matrix) =
  BEGIN
    FOR i := FIRST(data^) TO LAST(data^) DO
      FOR j := FIRST(data[0]) TO LAST(data[0]) DO
        IO.Put(Fmt.F("%3s", Fmt.Int(data[i, j])));
      END;
      IO.Put("\n");
    END;
  END Print;
 
BEGIN
  Print(Create(5));
END ZigZag.