穷举是计算机强项,也是解决许多问题的常用方法.但适当地前期处理可以大大减少计算量,从而几何级提速.列举一个九宫图的代码:
Sub test()
Dim i1 As Integer Dim i2 As Integer Dim i3 As Integer Dim i4 As Integer Dim i5 As Integer Dim i6 As Integer Dim i7 As Integer Dim i8 As Integer Dim i9 As Integer Dim strTmp As String Dim t(1 To 9) As String '2 9 4 '7 5 3 '6 1 8 For i1 = 1 To 9 t(1) = i1 strTmp = "0" & i1 For i2 = 1 To 9 strTmp = "0" & i1 If InStr(1, strTmp, i2) = 0 Then t(2) = i2 strTmp = "0" & i1 & i2 For i3 = 1 To 9 strTmp = "0" & i1 & i2 If InStr(1, strTmp, i3) = 0 Then t(3) = i3 strTmp = "0" & i1 & i2 & i3 For i4 = 1 To 9 strTmp = "0" & i1 & i2 & i3 If InStr(1, strTmp, i4) = 0 Then t(4) = i4 strTmp = "0" & i1 & i2 & i3 & i4 For i5 = 1 To 9 strTmp = "0" & i1 & i2 & i3 & i4 If InStr(1, strTmp, i5) = 0 Then t(5) = i5 strTmp = "0" & i1 & i2 & i3 & i4 & i5 For i6 = 1 To 9 strTmp = "0" & i1 & i2 & i3 & i4 & i5 If InStr(1, strTmp, i6) = 0 Then t(6) = i6 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 For i7 = 1 To 9 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 If InStr(1, strTmp, i7) = 0 Then t(7) = i7 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 & i7 For i8 = 1 To 9 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 & i7 If InStr(1, strTmp, i8) = 0 Then t(8) = i8 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 & i7 & i8 For i9 = 1 To 9 strTmp = "0" & i1 & i2 & i3 & i4 & i5 & i6 & i7 & i8 If InStr(1, strTmp, i9) = 0 Then t(9) = i9 If t(1) + t(2) + t(3) = 15 Then If t(1) + t(4) + t(7) = 15 Then If t(2) + t(5) + t(8) = 15 Then If t(3) + t(6) + t(9) = 15 Then If t(4) + t(5) + t(6) = 15 Then If t(7) + t(8) + t(9) = 15 Then If t(1) + t(5) + t(9) = 15 Then If t(3) + t(5) + t(7) = 15 Then Debug.Print Join(t, "") Exit Sub End If End If End If End If End If End If End If End If End If DoEvents Next i9 End If Next i8 End If Next i7 End If Next i6 End If Next i5 End If Next i4 End If Next i3 End If Next i2 Next i1
MsgBox "ok"
End Sub
晕不晕????????????????
先做适当的手工计算,优化后:
'易知九宫图中间为5,关于中心对称位置之和为10,分析如下:
' a b c
' d 5 10-d
' 10-c 10-b 10-a
'if a is an odd,c is an odd ,then 10-a is an odd,10-c is odd,so b,d,10-d,10-b are all odds(paradox) 'if a is an odd,c is an even ,then 10-a is an odd,10-c is even,so b,d,10-d,10-b are all evens(paradox)
'if a is an even,c is an odd ,then 10-a is an even,10-c is odd,so b,d,10-d,10-b are all evens(paradox)
'if a is an even,c is an even ,then 10-a is an even,10-c is even,so b,d,10-d,10-b are all odds(maybe)
'so a ,c must be evens; b,d must be odds
Sub test2() Dim nine() As String Dim a As Integer, b As Integer, c As Integer, d As Integer, i As Integer, k As Integer For a = 2 To 8 Step 2 For b = 1 To 9 Step 2 For c = 2 To 8 Step 2 For d = 1 To 9 Step 2 If a + b + c = 15 And a + d - c = 5 And a + c <> 10 And b + d <> 10 And b <> 5 And d <> 5 Then k = k + 1 ReDim Preserve nine(1 To k) nine(k) = StrConv(a & b & c & vbCrLf & d & "5" & (10 - d) & vbCrLf & (10 - c) & (10 - b) & (10 - a), vbWide) '全角显示 End If Next: Next: Next: Next For i = 1 To k Debug.Print "九宫图之" & i Debug.Print nine(i) Next End Sub
|