Private Sub btnCmd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCmd.Click
CreateMagicSquare(txtSize.Text, lvwDisplay)
End Sub
Private Function CreateMagicSquare(ByVal sSize As Short, ByRef lvwList As ListView)
If IsEven(sSize) = True Then
MsgBox("Error: This Function Does NOT Support Even Numbers!!!")
Exit Function
End If
Dim asMagicSquare(sSize, sSize) As Short ' Create The Array to hold the square
Dim sCount As Short ' Hold counting place
Dim sCurX As Short ' Holds The Vertical Position in array(magic Square)
Dim sCurY As Short ' Holds the Horizontal Position in array
Dim sOldX As Short ' Holds old sCurX (Needed because of overwrite)
Dim sOldY As Short ' Holds old sCurY (Needed because of overwrite)
'Must Start In The MIDDLE of the First row so:
sCurX = 1 ' This is give does not change
sCurY = ((sSize - 1) / 2) + 1 ' Find Middle
'Write Frist Number
asMagicSquare(sCurX - 1, sCurY - 1) = 1 ' Always 1
For sCount = 2 To (sSize * sSize)
sOldX = sCurX
sOldY = sCurY
If sCurX = 1 Then
'We are In The Top Row and cant Move Up anymore
sCurX = sSize 'move to bottom row
Else
sCurX = sCurX - 1
End If
If sCurY < sSize Then
sCurY = sCurY + 1
Else
sCurY = 1
End If
'Check If we are going to overwrite
If asMagicSquare(sCurX - 1, sCurY - 1) <> Nothing Then
'We are going to overwrite
'so we must go below the last number we wrote
sCurX = sOldX + 1
sCurY = sOldY
If asMagicSquare(sCurX - 1, sCurY - 1) <> Nothing Then
MsgBox("Error Overwrite!! AGAIN!")
End If
End If
'Write sCount to position
asMagicSquare(sCurX - 1, sCurY - 1) = sCount
Next
DisplayArray(asMagicSquare, lvwList)
End Function
Private Function IsEven(ByVal lngNumber As Long) As Boolean
If lngNumber = 0 Then
Return False
End If
If (lngNumber Mod 2) = 0 Then
Return True
End If
End Function
Private Function DisplayArray(ByVal asArray(,) As Short, ByRef lvwList As ListView)
Dim x As Short
Dim y As Short
'Setup listview
lvwList.Clear() ' Just Incase there is data in the list already
lvwList.View = View.Details
Dim col As New ListView.ColumnHeaderCollection(lvwList)
col.Clear()
For x = 0 To (UBound(asArray) - 1)
'Add a Colum to the listview
col.Add("", 40, HorizontalAlignment.Center)
lvwList.Items.Add(asArray(x, 0))
For y = 1 To (UBound(asArray) - 1)
lvwList.Items(x).SubItems.Add(asArray(x, y))
Next
Next
End Function
End Class