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


zigzag1:=proc(n)
  uses ArrayTools;
  local i,u,v,a;
  u:=Replicate(<-1,1>,n):
  v:=Vector[row](1..n,i->i*(2*i-3)):
  v:=Reshape(<v+~1,v+~2>,2*n):
  a:=Matrix(n,n):
  for i to n do
    a[...,i]:=v[i+1..i+n];
    v+=u
  od:
  a
end:
 
zigzag2:=proc(n)
  local i,v,a;
  a:=zigzag1(n);
  v:=Vector(1..n-1,i->i^2);
  for i from 2 to n do
    a[n+2-i..n,i]-=v[1..i-1]
  od;
  a
end: