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


 
(* ****** ****** *)
//
#include
"share/atspre_define.hats" // defines some names
#include
"share/atspre_staload.hats" // for targeting C
#include
"share/HATS/atspre_staload_libats_ML.hats" // for ...
//
(* ****** ****** *)
//
extern
fun
Zig_zag_matrix(n: int): void
//
(* ****** ****** *)
 
fun max(a: int, b: int): int =
  if a > b then a else b
 
fun movex(n: int, x: int, y: int): int =
  if y < n-1 then max(0, x-1) else x+1
 
fun movey(n: int, x: int, y: int): int =
  if y < n-1 then y+1 else y
 
fun zigzag(n: int, i: int, row: int, x: int, y: int): void =
  if i = n*n then ()
  else
    let
      val () = (if x = row then begin print i; print ','; end else ())
      //val () = (begin print x; print ' '; print y; print ' '; print i; print ' '; end)
      val nextX: int = if ((x+y) % 2) = 0 then movex(n, x, y) else movey(n, y, x)
      val nextY: int = if ((x+y) % 2) = 0 then movey(n, x, y) else movex(n, y, x)
    in
      zigzag(n, i+1, row, nextX, nextY)
    end
 
implement
Zig_zag_matrix(n) =
  let
    fun loop(row: int): void =
      if row = n then () else
        let
          val () = zigzag(n, 0, row, 0, 0)
          val () = println!(" ")
        in
          loop(row + 1)
        end
  in
    loop(0)
  end
 
(* ****** ****** *)
 
implement
main0() = () where
{
  val () = Zig_zag_matrix(5)
} (* end of [main0] *)
 
(* ****** ****** *)
 