八個數字的排列組合 (VB)
八個數字排列組合不重複
於數學上就是8!=40320種組合
而程式上該如何列出這些排列
本範例寫在模組內
如果是Excel VBA,可以直接輸出至Excel
如果是VB6,請將結果開啟新檔輸出即可
程式架構為八層迴圈
外層用過的數字
內層就不能使用
因此
用字串挑選的方式比較能簡化程式
程式如下
Sub codenum()
For i1 = 1 To 8
allnum1 = "12345678"
a1 = Mid(allnum1, i1, 1)
For i2 = 1 To 7
allnum2 = Mid(allnum1, 1, i1 - 1) & Mid(allnum1, i1 + 1, 8 - i1)
a2 = Mid(allnum2, i2, 1)
For i3 = 1 To 6
allnum3 = Mid(allnum2, 1, i2 - 1) & Mid(allnum2, i2 + 1, 7 - i2)
a3 = Mid(allnum3, i3, 1)
For i4 = 1 To 5
allnum4 = Mid(allnum3, 1, i3 - 1) & Mid(allnum3, i3 + 1, 6 - i3)
a4 = Mid(allnum4, i4, 1)
For i5 = 1 To 4
allnum5 = Mid(allnum4, 1, i4 - 1) & Mid(allnum4, i4 + 1, 5 - i4)
a5 = Mid(allnum5, i5, 1)
For i6 = 1 To 3
allnum6 = Mid(allnum5, 1, i5 - 1) & Mid(allnum5, i5 + 1, 4 - i5)
a6 = Mid(allnum6, i6, 1)
For i7 = 1 To 2
allnum7 = Mid(allnum6, 1, i6 - 1) & Mid(allnum6, i6 + 1, 3 - i6)
a7 = Mid(allnum7, i7, 1)
For i8 = 1 To 1
allnum8 = Mid(allnum7, 1, i7 - 1) & Mid(allnum7, i7 + 1, 2 - i7)
a8 = allnum8
i = i + 1
code = a1 & a2 & a3 & a4 & a5 & a6 & a7 & a8
Sheet1.Cells(i, 1) = code
Next i8
Next i7
Next i6
Next i5
Next i4
Next i3
Next i2
Next i1
End Sub
參考來源:http://tw.myblog.yahoo.com/teddybear-13/article?mid=343&prev=-1&next=342
如有錯誤 歡迎指正