Results 1 to 2 of 2

Thread: algorithm for computing combinations of elements

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Aug 2001
    Location
    India
    Posts
    203

    algorithm for computing combinations of elements

    Hi guys...Im trying to figure out an algorithm for calculating the various combinations of n elements...Iv come to the conclusion that its gotta be a recursive call inside a for loop...and thats where Im stuck...need help here

    what I need
    Combinat(ABC)=

    ABC
    ACB
    BAC
    BCA
    CAB
    CBA

  2. #2
    Only Slightly Obsessive jemidiah's Avatar
    Join Date
    Apr 2002
    Posts
    2,431
    Here's the cheap method:

    VB Code:
    1. Private Sub Command1_Click()
    2. Dim tempStr As String
    3. Dim tempChar As String
    4. Dim StoreStr As String
    5. Dim StrLen As Integer
    6. Dim tempVal As Long
    7.  
    8. StrLen = 3
    9.  
    10. Randomize
    11. tempVal = (StrLen + 2) * Factorial(StrLen)
    12. Do Until Len(StoreStr) = tempVal
    13.     tempStr = ""
    14.     For i = 1 To StrLen
    15. ReTempChar:
    16.         tempChar = Chr(Asc("A") + Int(Rnd * StrLen))
    17.         If InStr(tempStr, tempChar) Then GoTo ReTempChar
    18.         tempStr = tempStr & tempChar
    19.     Next i
    20.     If InStr(StoreStr, tempStr) = 0 Then StoreStr = StoreStr & tempStr & vbCrLf
    21.     Me.Caption = Int(Len(StoreStr) / tempVal * 100)
    22. Loop
    23.  
    24. Text1.Text = StoreStr
    25. End Sub
    26.  
    27. Private Function Factorial(myNum As Integer) As Double
    28. Dim Factorial_i As Long
    29. Factorial = 1
    30.  
    31. For Factorial_i = 1 To myNum
    32.     Factorial = Factorial * Factorial_i
    33. Next Factorial_i
    34. End Function

    It's extremely fast until after StrLen is 6. 7 isn't bad, 8 would take a while. I'm sure it can handle up till 11 or so (overflows), though it would get much slower.

    Edit: Fixed it so it only used every character once per permutation.
    Last edited by jemidiah; Feb 17th, 2004 at 02:07 AM.
    The time you enjoy wasting is not wasted time.
    Bertrand Russell

    <- Remember to rate posts you find helpful.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width