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


 
#!/bin/ksh
 
# Produce a zig-zag array.
 
#	# Variables:
#
integer DEF_SIZE=5			# Default size = 5
arr_size=${1:-$DEF_SIZE}	# $1 = size, or default
 
    #	# Externals:
    #
 
#	# Functions:
#
 
 
 ######
# main #
 ######
integer i j n
typeset -a zzarr
 
for (( i=n=0; i<arr_size*2; i++ )); do
	for (( j= (i<arr_size) ? 0 : i-arr_size+1; j<=i && j<arr_size; j++ )); do
		(( zzarr[(i&1) ? j*(arr_size-1)+i : (i-j)*arr_size+j] = n++ ))
	done
done
 
for ((i=0; i<arr_size*arr_size; i++)); do
	printf "%3d " ${zzarr[i]}
	(( (i+1)%arr_size == 0 )) && printf "\n"
done