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


 
(*
    From the library.
*)
DEFINE reverse == [] swap shunt;
       shunt   == [swons] step.
 
(*
    Split according to the parameter given.
*)
DEFINE take-drop  == [dup] swap dup [[] cons [take swap] concat concat] dip []
                     cons concat [drop] concat.
 
(*
    Take the first of a list of lists.
*)
DEFINE take-first == [] cons 3 [dup] times [dup] swap concat [take [first] map
                     swap dup] concat swap concat [drop swap] concat swap
                     concat [take [rest] step []] concat swap concat [[cons]
                     times swap concat 1 drop] concat.
 
DEFINE zigzag ==
 
(*
    Use take-drop to generate a list of lists.
*)
4 [dup] times 1 swap from-to-list swap pred 1 swap from-to-list reverse concat
swap dup * pred 0 swap from-to-list swap [take-drop i] step [pop list] [cons]
while
 
(*
    The odd numbers must be modified with reverse.
*)
[dup size 2 div popd [1 =] [pop reverse] [pop] ifte] map
 
(*
    Take the first of the first of n lists.
*)
swap dup take-first [i] cons times pop
 
(*
    Merge the n separate lists.
*)
[] [pop list] [cons] while
 
(*
    And print them.
*)
swap dup * pred 'd 1 1 format size succ [] cons 'd swons [1 format putchars]
concat [step '\n putch] cons step.
 
11 zigzag.