有一个着名且最快的排列代码,没有任何"功能"对于VB .Net来说,只排列几行中的数字,不幸的是我无法记住。
有没有人知道这段代码?或者知道这样吗?
代码的某些部分在这里:
更新:我发现了它。这里的所有工作代码:
Dim L(4) As Byte
Dim I As Byte
Dim K As Byte
Dim J As Byte
Dim RESULTS As String
Dim UB, UBm1 As Integer
L = {1, 2, 3, 4, 5}
UB = L.GetUpperBound(0)
UBm1 = UB - 1
Do
I = UBm1
Do While I > 0 And L(I) >= L(I + 1)
I -= 1
Loop
K = L(I)
J = UB
Do While J > 0 And L(J) <= K
J -= 1
Loop
RESULTS = L(0) & "," & L(1) & "," & L(2) & "," & L(3) & "," & L(4)
L(I) = L(J)
L(J) = K
Array.Reverse(L, I + 1, UB - I)
Loop While J
答案 0 :(得分:0)
好像你正在寻找这个......
http://www.cut-the-knot.org/do_you_know/AllPerm.shtml (2.字典顺序并找到下一个排列)
......?
如果您是,I
和J
的起始值不正确(它们应分别为4和5而不是3和4)。
(我知道该示例使用swap
,但可以用单个以冒号分隔的行替换。)
Dim L(4) As Byte
L = {1, 2, 3, 4, 5}
Dim K as Byte
For N as integer = 1 to 120 'No. of permutations: 5!
Dim I As Byte = 4, J as Byte = 5
While L(I - 1) >= L(I)
I -= 1
End While
While L(J - 1) <= L(I - 1)
J -= 1
End While
K = L(I - 1) : L(I - 1) = L(J - 1) : L(J - 1) = K
I += 1 : J = 5
While I < J
K = L(I - 1) : L(I - 1) = L(J - 1) : L(J - 1) = K
I += 1 : J -= 1
End While
Dim RESULT as String = L(0) & "," & L(1) & "," & L(2) & "," & L(3) & "," & L(4)
'Export / print RESULT as you like, e.g. Console.WriteLine or something
Next
答案 1 :(得分:0)
为了获得一组自然数的排列(推荐小于10,虽然它可能大于10),这个 VBA Excel 子程序非常快而且很短。我相信将其转换为VB.NET很容易。看看。
Const P = 5 'Recommended Max P = 9
Dim m As Long, PArray(1 To 1000, 1 To P) 'Recommended Max 9! = 362880
Public Sub PermutationNaturalNumber()
Dim Q(1 To P) As Long
For m = 1 To P: Q(m) = m: Next: m = 0
PermutationGenerator P, Q
Range("A1").Resize(UBound(PArray), P) = PArray: End
End Sub
Sub PermutationGenerator(n As Long, Q() As Long)
Dim i As Long, j As Long, k As Long
If n > 1 Then
For i = 1 To n - 1
PermutationGenerator n - 1, Q
If n Mod 2 = 1 Then j = 1 Else j = i
k = Q(j): Q(j) = Q(n): Q(n) = k
Next
PermutationGenerator n - 1, Q
Else
m = m + 1: For i = 1 To P: PArray(m, i) = Q(i): Next
End If
End Sub
P
可以是任何自然数,在这种情况下是{1,2,3,4,5}。确保用P改变PArray
的上限!意义(P*(P-1)*(P-2)*...*1
)。