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


DEFINE MAX_SIZE="10"
DEFINE MAX_MATRIX_SIZE="100"
 
INT FUNC Index(BYTE size,x,y)
RETURN (x+y*size)
 
PROC PrintMatrix(BYTE ARRAY a BYTE size)
  BYTE i,j,v
 
  FOR j=0 TO size-1
  DO
    FOR i=0 TO size-1
    DO
      v=a(Index(size,i,j))
      IF v<10 THEN
        Print("  ")
      ELSE
        Print(" ")
      FI
      PrintB(v)
    OD
    PutE()
  OD
RETURN
 
PROC FillMatrix(BYTE ARRAY a BYTE size)
  BYTE start,end
  INT dir,i,j
 
  start=0 end=size*size-1
  i=0 j=0 dir=1
 
  DO
    a(Index(size,i,j))=start
    a(Index(size,size-1-i,size-1-j))=end
    start==+1 end==-1
    i==+dir j==-dir
    IF i<0 THEN
      i==+1 dir=-dir
    ELSEIF j<0 THEN
      j==+1 dir=-dir
    FI
  UNTIL start>=end
  OD
 
  IF start=end THEN
    a(Index(size,i,j))=start
  FI
RETURN
 
PROC Test(BYTE size)
  BYTE ARRAY mat(MAX_MATRIX_SIZE)
 
  PrintF("Matrix size: %B%E",size)
  FillMatrix(mat,size)
  PrintMatrix(mat,size)
  PutE()
RETURN
 
PROC Main()
  Test(5)
  Test(6)
RETURN