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


' FB 1.05.0 Win64
 
Dim As Integer n
 
Do
  Input "Enter size of matrix "; n
Loop Until n > 0 
 
Dim zigzag(1 To n, 1 To n) As Integer '' all zero by default
 
' enter the numbers 0 to (n^2 - 1) in the matrix's anti-diagonals
zigzag(1, 1) = 0
If n > 1 Then
  Dim As Integer row = 0, col = 3
  Dim As Boolean down = true, increment = true
  Dim As Integer i = 0, j = 2, k
  Do
    If down Then
      For k = 1 To j
        i += 1
        row += 1
        col -= 1
        zigzag(row, col) = i
      Next     
      down = false
    Else
      For k = 1 To j
        i += 1
        row -= 1
        col += 1
        zigzag(row, col) = i
      Next   
      down = true
    End If
    If increment Then
      j += 1
      If j > n Then
        j = n - 1
        increment = false
      End If
    Else
      j -= 1
      If j = 0 Then Exit Do
    End If
    If down AndAlso increment Then
      col += 2
      row -= 1    
    ElseIf Not Down AndAlso increment Then
      row += 2
      col -= 1
    ElseIf down AndAlso Not increment Then
      col += 1 
    Else '' Not down AndAlso NotIncrement 
      row += 1
    End If       
  Loop
End If
 
' print zigzag matrix if n < 20 
Print
If n < 20 Then
  For i As Integer = 1 To n
    For j As Integer = 1 To n
      Print Using "####"; zigzag(i, j); 
    Next j
    Print
  Next i
Else 
  Print "Matrix is too big to display on 80 column console"
End If
 
Print
Print "Press any key to quit"
Sleep