EXCEL VBA]EXCEL中用递归实现任意n(3≤n≤256)阶幻方

下面代码将实现任意n(3≤n≤256)阶幻方,显示在EXCEL的 A1:IV256中

Sub magicsquare(ByVal n As Long, ByRef matrix())
Dim i As Long, j As Long, k As Long, p As Long, a(), temp As New Collection
ReDim matrix(1 To 256, 1 To 256)
If n < 3 Then MsgBox "n must be larger than 2! ": Exit Sub
If n Mod 4 = 0 Then
ReDim a(1 To n, 1 To n)
ReDim b(1 To n, 1 To n)
For i = 1 To n
For j = 1 To n
matrix(i, j) = IIf((i Mod 4) / 2 = (j Mod 4) / 2, n * n + 1 - (i - 1) * n - j, (i - 1) * n + j)
Next
Next

Else
If n Mod 4 = 2 Then
p = n / 2
ReDim a(1 To p, 1 To p)
magicsquare p, a

For i = 1 To p
For j = 1 To p
matrix(i, j) = a(i, j)
matrix(i + p, j) = a(i, j) + 3 * p * p
matrix(i, j + p) = a(i, j) + 2 * p * p
matrix(i + p, j + p) = a(i, j) + p * p
Next
Next


For i = 1 To (n - 2) / 4
temp.Add i
Next
For i = 3 * (n - 2) / 4 + 1 To n
temp.Add i
Next

For i = 1 To p
For j = 1 To temp.Count
k = matrix(i, temp(j))
matrix(i, temp(j)) = matrix(i + p, temp(j))
matrix(i + p, temp(j)) = k
Next
Next

Else

For j = 0 To n - 1
For i = 0 To n - 1
If j = 0 Then matrix(j + 1, i + 1) = IIf(i >= (n - 1) / 2, 0, n * (n + 1)) + (i - (n - 1) / 2) * (n + 2) + 1
If j > 0 Then matrix(j + 1, i + 1) = 1 + (n * n + matrix(j, i + 1) + IIf(matrix(j, i + 1) Mod n = 0, 0, n)) Mod n ^ 2
Next
Next
End If
End If
End Sub
 
Sub makemagicsquare()
Dim arr(), n As Long

Randomize
n = CLng(InputBox("please enter an integer", "infomation", 3+Int(Rnd*254)))
magicsquare n, arr
Range("a1").Resize(256, 256) = arr
Range("a1").Resize(256, 256).Columns.AutoFit
End Sub

 

你可能感兴趣的:(VBA)