Looping in a spiral

前端 未结 30 2714
独厮守ぢ
独厮守ぢ 2020-11-22 15:07

A friend was in need of an algorithm that would let him loop through the elements of an NxM matrix (N and M are odd). I came up with a solution, but I wanted to see if my fe

30条回答
  •  天涯浪人
    2020-11-22 15:28

    Davidont's excellent solution in VB.Net

        Public Function Spiral(n As Integer) As RowCol
        ' given n an index in the squared spiral
        ' p the sum of point in inner square
        ' a the position on the current square
        ' n = p + a
        ' starts with row 0 col -1
        Dim r As Integer = CInt(Math.Floor((Math.Sqrt(n + 1) - 1) / 2) + 1)
    
        ' compute radius : inverse arithmetic sum of 8+16+24+...=
        Dim p As Integer = (8 * r * (r - 1)) \ 2
        ' compute total point on radius -1 : arithmetic sum of 8+16+24+...
    
        Dim en As Integer = r * 2
        ' points by face
    
        Dim a As Integer = (1 + n - p) Mod (r * 8)
        ' compute the position and shift it so the first is (-r,-r) but (-r+1,-r)
        ' so square can connect
    
        Dim row As Integer
        Dim col As Integer
    
        Select Case Math.Floor(a \ (r * 2))
            ' find the face : 0 top, 1 right, 2, bottom, 3 left
            Case 0
                row = a - r
                col = -r
            Case 1
                row = r
                col = (a Mod en) - r
            Case 2
                row = r - (a Mod en)
                col = r
            Case 3
                row = -r
                col = r - (a Mod en)
        End Select
    
        Return New RowCol(row, col)
    End Function
    

提交回复
热议问题