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


proc zigzag {size} {
    set m [lrepeat $size [lrepeat $size .]]
    set x 0; set dx -1
    set y 0; set dy 1
 
    for {set i 0} {$i < $size ** 2} {incr i} {
        if {$x >= $size} {
            incr x -1
            incr y 2
            negate dx dy
        } elseif {$y >= $size} {
            incr x 2
            incr y -1
            negate dx dy
        } elseif {$x < 0 && $y >= 0} {
            incr x
            negate dx dy
        } elseif {$x >= 0 && $y < 0} {
            incr y
            negate dx dy
        }
        lset m $x $y $i
        incr x $dx
        incr y $dy
    }
    return $m
}
 
proc negate {args} {
    foreach varname $args {
        upvar 1 $varname var
        set var [expr {-1 * $var}]
    }
}
 
print_matrix [zigzag 5]