Click to See Complete Forum and Search --> : algorithm for computing combinations of elements
udit99
Feb 16th, 2004, 10:44 PM
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
jemidiah
Feb 16th, 2004, 11:59 PM
Here's the cheap method:
Private Sub Command1_Click()
Dim tempStr As String
Dim tempChar As String
Dim StoreStr As String
Dim StrLen As Integer
Dim tempVal As Long
StrLen = 3
Randomize
tempVal = (StrLen + 2) * Factorial(StrLen)
Do Until Len(StoreStr) = tempVal
tempStr = ""
For i = 1 To StrLen
ReTempChar:
tempChar = Chr(Asc("A") + Int(Rnd * StrLen))
If InStr(tempStr, tempChar) Then GoTo ReTempChar
tempStr = tempStr & tempChar
Next i
If InStr(StoreStr, tempStr) = 0 Then StoreStr = StoreStr & tempStr & vbCrLf
Me.Caption = Int(Len(StoreStr) / tempVal * 100)
Loop
Text1.Text = StoreStr
End Sub
Private Function Factorial(myNum As Integer) As Double
Dim Factorial_i As Long
Factorial = 1
For Factorial_i = 1 To myNum
Factorial = Factorial * Factorial_i
Next Factorial_i
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.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.