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


PROGRAM ZIG_ZAG
 
!$DYNAMIC
     DIM ARRAY%[0,0]
 
BEGIN
     SIZE%=5
     !$DIM ARRAY%[SIZE%-1,SIZE%-1]
 
     I%=1
     J%=1
     FOR E%=0 TO SIZE%^2-1 DO
          ARRAY%[I%-1,J%-1]=E%
          IF ((I%+J%) AND 1)=0 THEN
              IF J%<SIZE% THEN J%+=1 ELSE I%+=2 END IF
              IF I%>1 THEN I%-=1 END IF
           ELSE
              IF I%<SIZE% THEN I%+=1 ELSE J%+=2 END IF
              IF J%>1 THEN J%-=1 END IF
          END IF
     END FOR
 
     FOR ROW%=0 TO SIZE%-1 DO
         FOR COL%=0 TO SIZE%-1 DO
            WRITE("###";ARRAY%[ROW%,COL%];)
         END FOR
         PRINT
     END FOR
END PROGRAM