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


beads 1 program 'Zig-zag Matrix'
 
calc main_init
	var test : array^2 of num = create_array(5)
	printMatrix(test)
 
calc create_array(
	dimension:num
	):array^2 of num
	var
		result : array^2 of num
		lastValue = dimension^2 - 1
		loopFrom
		loopTo
		row
		col
		currDiag = 0
		currNum = 0
	loop
		if (currDiag < dimension)	// if doing the upper-left triangular half
			loopFrom = 1
			loopTo = currDiag + 1
		else	// doing the bottom-right triangular half
			loopFrom = currDiag - dimension + 2
			loopTo = dimension
		loop count:c from:loopFrom to:loopTo
			var i = loopFrom + c - 1
			if (rem(currDiag, 2) == 0)	// want to fill upwards
				row = loopTo - i + loopFrom
				col = i
			else	// want to fill downwards
				row = i
				col = loopTo - i + loopFrom
			result[row][col] = currNum
			inc currNum
		inc currDiag
		if (currNum > lastValue)
			exit
	return result
 
calc printMatrix(
	matrix:array^2 of num
	)
	var dimension = tree_count(matrix)
	var maxDigits = 1 + lg((dimension^2-1), base:10) 
	loop across:matrix ptr:rowp index:row
		var tempstr : str
		loop across:rowp index:col
			tempstr = tempstr & " " & to_str(matrix[row][col], min:maxDigits)
		log(tempstr)