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)


Option Explicit
 
Sub Main()
    print2dArray getSpiralArray(5)
End Sub
 
Function getSpiralArray(dimension As Integer) As Integer()
    ReDim spiralArray(dimension - 1, dimension - 1) As Integer
 
    Dim numConcentricSquares As Integer
    numConcentricSquares = dimension \ 2
    If (dimension Mod 2) Then numConcentricSquares = numConcentricSquares + 1
 
 
    Dim j As Integer, sideLen As Integer, currNum As Integer
    sideLen = dimension
 
    Dim i As Integer
    For i = 0 To numConcentricSquares - 1
        ' do top side
        For j = 0 To sideLen - 1
            spiralArray(i, i + j) = currNum
            currNum = currNum + 1
        Next
 
        ' do right side
        For j = 1 To sideLen - 1
            spiralArray(i + j, dimension - 1 - i) = currNum
            currNum = currNum + 1
        Next
 
        ' do bottom side
        For j = sideLen - 2 To 0 Step -1
            spiralArray(dimension - 1 - i, i + j) = currNum
            currNum = currNum + 1
        Next
 
        ' do left side
        For j = sideLen - 2 To 1 Step -1
            spiralArray(i + j, i) = currNum
            currNum = currNum + 1
        Next
 
        sideLen = sideLen - 2
    Next
 
    getSpiralArray = spiralArray()
End Function
 
Sub print2dArray(arr() As Integer)
    Dim row As Integer, col As Integer
    For row = 0 To UBound(arr, 1)
        For col = 0 To UBound(arr, 2) - 1
            Debug.Print arr(row, col),
        Next
        Debug.Print arr(row, UBound(arr, 2))
    Next
End Sub