Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Letter permutations/recursive algorithms

Status
Not open for further replies.

MisterC

IS-IT--Management
Apr 19, 2001
501
US
I'm no good with recursive algorithms, but I know I've seen one that will do this for me. I need to know all permutations of a set of letters. Example: If the input is "ABC", the output would be:
Code:
     A    AC     CB     BCA
     B    BA     ABC    CAB
     C    BC     ACB    CBA
     AB   CA     BAC
Does anyone have a clue?
 
There's probably a better way to do this. This can be scaled up for a larger input.


Dim X
Dim Y
Dim Z
Dim TempStr(100)

Private Sub Command1_Click()
For X = 1 To Len(Text1)
TempStr(X) = Mid$(Text1, X, 1)
Text2 = Text2 & TempStr(X) & Chr$(9)
Next

For Z = 1 To Len(Text1)
For X = 1 To Len(Text1)
If Z <> X Then Text2 = Text2 & TempStr(Z) & TempStr(X) & Chr$(9)
Next
Next

For Y = 1 To Len(Text1)
For Z = 1 To Len(Text1)
For X = 1 To Len(Text1)
If Y <> Z And Y <> X And Z <> Y And Z <> X Then Text2 = Text2 & TempStr(Y) & TempStr(Z) & TempStr(X) & Chr$(9)
Next
Next
Next

End Sub
 
Thanks for your reply!
Your code works fine for a string with 3 or less characters, but would need to be modified if there were more.
I need something recursive that doesn't require modification for different string lengths.
Any ideas?
 
Dont.

The recursion for permutations and combinations of more than a very few (approx 10?) &quot;tokens&quot; is simply not possible in VB, as the system will run out of resources.

Remember that the permutations is n! so 10! is already a LARGE number (3628800) doing a recursive routine means that you have n! copies of the routine &quot;loaded&quot; simultaneously.

MichaelRed
m.red@att.net

There is never time to do it right but there is always time to do it over
 
Michael,
I understand, but all I need is 7 (n!=5040). Is there a non-recursive method to do this?
Thanks!
 
I recall 'tossing the baby out with ... '. It was a nested set of loops, with the nesting level and an array dimensioned to the number of results, based on the number of tokens. I just used an index within the array to denote the token to be assigned. I never went the last mile (actually assigning the tokens and outputting the final lists), as once the token index for a position was known the remainder was just a lookup. Each loop iteration provided the assignment of ONE element in the array, so -even w/o recursion- it became very slow for more than a few tokens. MichaelRed
m.red@att.net

There is never time to do it right but there is always time to do it over
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top