Task

Produce a spiral array.



A   spiral array   is a square arrangement of the first    N2   natural numbers,   where the

numbers increase sequentially as you go around the edges of the array spiraling inwards.



For example, given   5,   produce this array:

 0  1  2  3  4
15 16 17 18  5
14 23 24 19  6
13 22 21 20  7
12 11 10  9  8



Related tasks

   Zig-zag matrix 
   Identity_matrix
   Ulam_spiral_(for_primes)


' FB 1.05.0 Win64
 
Enum Direction
  across 
  down
  back
  up
End Enum
 
Dim As Integer n
 
Do
  Input "Enter size of matrix "; n
Loop Until n > 0 
 
Dim spiral(1 To n, 1 To n) As Integer '' all zero by default
 
' enter the numbers 0 to (n^2 - 1) spirally in the matrix
 
Dim As Integer row = 1, col = 1, lowRow = 1, highRow = n, lowCol = 1, highCol = n
Dim d As Direction = across
 
For i As Integer = 0 To (n * n - 1)
  spiral(row, col) = i
  Select Case d
    Case across
      col += 1
      If col > highCol Then
        col = highCol
        row += 1
        d = down
      End if
    Case down
      row += 1
      If row > highRow Then
        row = highRow
        col -= 1
        d = back
      End if
    Case back
      col -= 1
      If col < lowCol Then
        col = lowCol
        row -= 1
        d = up
        lowRow += 1        
      End If
    Case up
      row -= 1
      If row < lowRow Then
        row = lowRow
        col += 1
        d = across
        highRow -= 1
        lowCol += 1
        highCol -= 1
      End If
  End Select
Next 
 
' print spiral 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 "####"; spiral(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