Fozzedout - 4 days ago 5
Vb.net Question

# 2D Array Rotation and Rotating a Point in vb.net

I have written a 2D array rotation which works just fine, however I have a point that is focused on a single location on the array and displays a "!" instead of the number when displaying the array.

I had thought that if I checked the point during the array rotation, and then changed the point position to the new array position, the focus point would then rotate with the array, however, the new point location just doesn't match the rotated point.

In the example, I'm focusing on the number "5" (position 1,1), and should always display the "!" instead of "5".

This rotation works for a focal point of 0,0, but not for other points. Can someone please point out to me what I'm doing wrong and explain why the logic doesn't always work?

``````Public Module Module1

Dim focalX As Integer = 1
Dim focalY As Integer = 1

Sub Main()
Dim src(,) As String =
{
{"1", "2", "3"},
{"4", "5", "6"},
{"7", "8", "9"},
{"0", "1", "2"}
}

ShowArray(src)

src = RotatedCW(src)

ShowArray(src)

src = RotatedCW(src)

ShowArray(src)

src = RotatedCW(src)

ShowArray(src)

Console.WriteLine()
Console.WriteLine("Press Enter to exit...")
End Sub

Sub ShowArray(src(,) As String)
Console.WriteLine(focalX & ", " & focalY)

For i = 0 To src.GetUpperBound(0)
For j = 0 To src.GetUpperBound(1)
If focalX = j And focalY = i Then
Console.Write("!" & " ")
Else
Console.Write(src(i, j) & " ")
End If
Next
Console.WriteLine()
Next

Console.WriteLine()
End Sub

Function RotatedCW(src(,) As String) As String(,)
Dim maxX As Integer = src.GetUpperBound(0)
Dim maxY As Integer = src.GetUpperBound(1)

Dim newArray(maxY, maxX) As String
For i = 0 To maxX
For j = 0 To maxY
newArray(j, maxX - i) = src(i, j)

If focalX = j And focalY = i Then
focalX = maxX - i
focalY = j
End If
Next
Next
Return newArray
End Function

End Module
``````

Just fixed your rotate function logic

``````Function RotatedCW(src(,) As String) As String(,)
Dim maxX As Integer = src.GetUpperBound(0)
Dim maxY As Integer = src.GetUpperBound(1)

Dim oldFocalY = focalY
focalY = focalX
focalX = maxX - oldFocalY

Dim newArray(maxY, maxX) As String
For i = 0 To maxX
For j = 0 To maxY
newArray(j, maxX - i) = src(i, j)
Next
Next
Return newArray
End Function
``````

Took the focal point assignments out of the loop because they are only done once and the math is very simple.