2011年7月16日 星期六

排列組合一

排列組合一

 從檔案 in.txt 讀入排列組合的項目,將所有可能的排列輸出到out.txt。

輸入範例:
 
a b c 1

輸出範例:

abc1
bac1
cab1
1abc
acb1
a1bc
bca1
b1ac
cba1
c1ab
1bac
1cab
ab1c
ba1c
ca1b
1acb
ac1b
a1cb
bc1a
b1ca
cb1a
c1ba
1bca
1cba
 
 

3 則留言:

  1. 現在覺得遞迴不難了。

    Dim Y() As String
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Do While Not EOF(1)
    Line Input #1, X
    Y = Split(X)
    Call ABC("")
    Loop
    Close #2
    Close #1
    End
    End Sub

    Sub ABC(A)
    If Len(A) = (UBound(Y) + 1) Then
    Print #2, A
    Else
    For I = 0 To UBound(Y)
    If InStr(A, Y(I)) = 0 Then Call ABC(A & Y(I))
    Next I
    End If
    End Sub

    ----in.txt-------
    a b c 1
    ----out.txt-------
    abc1
    ab1c
    acb1
    ac1b
    a1bc
    a1cb
    bac1
    ba1c
    bca1
    bc1a
    b1ac
    b1ca
    cab1
    ca1b
    cba1
    cb1a
    c1ab
    c1ba
    1abc
    1acb
    1bac
    1bca
    1cab
    1cba

    回覆刪除
  2. 佑好,
    程式正確,熟能生巧。

    回覆刪除
  3. Dim n As String, s
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2

    Input #1, n
    s = Split(n)
    Call Fun("")
    Close
    Close
    End
    End Sub

    Function Fun(a As String)

    If Len(a) = 4 Then
    Print #2, a
    Else
    For i = 0 To 3
    If InStr(a, s(i)) = 0 Then Call Fun(a & s(i))
    Next
    End If

    End Function

    回覆刪除