Find an algorithm (subroutine) that when called repeatedly with the same character-string variable that is initialized with n characters, all different, will cycle through all the permutations of those n characters, so that for example, when called 24 times with a string of length 4, will have cycled that string through all 24 permutations and returned it to its initial state.
Originally posted:
http://perplexus.info/forum.php?fid=6&tid=1057
This algorithm will let you go directly to the n(th) permutation of a string. Because the index is type long the max string length is 12. The code ignores the actual string data so duplicates in the seed will result in duplicate permutation. Written in Visual Basic.
Function permutation(ByVal seed As String, ByVal index As Long) As String
Dim buffer As String
Dim counter As Integer
Dim pointer As Integer
Dim place As Long
index = index Mod factorial(Len(seed))
If index < 0 Then index = index + factorial(Len(seed))
For counter = 1 To Len(seed) - 1
place = factorial(Len(seed) - 1)
pointer = index \ place + 1
buffer = buffer + Mid(seed, pointer, 1)
seed = Left(seed, pointer - 1) + Mid(seed, pointer + 1)
index = index Mod place
Next counter
permutation = buffer + seed
End Function
Function factorial(ByVal n As Integer) As Long
Dim product As Long
product = 1
For n = 1 To n
product = product * n
Next n
factorial = product
End Function
|
Posted by Axorion
on 2007-11-21 22:32:34 |