while I was writing a script for finding real-word anagrams of an arbitrary string of characters, I wrote the following helper function.
Forum user Helgef encouraged me enough to present my function as a stand-alone in this sub-forum. (Thank you)
Permutations() uses recursion to produce n! elements stored in an array, where n equals the length of the input.
E.g. you input "EASTERN" (n=7), and you get back an array with 5040 (n!) elements.
Code: Select all
;-------------------------------------------------------------------------------
Permutations(Word) { ; return an unsorted array with all permutations of Word
;-------------------------------------------------------------------------------
If (Len := StrLen(Word)) = 1
Return, [Word]
Result := []
Loop, %Len% {
Split1 := SubStr(Word, 1, A_Index - 1) ; before pos
Split2 := SubStr(Word, A_Index, 1) ; at pos
Split3 := SubStr(Word, A_Index + 1) ; after pos
For each, Perm in Permutations(Split1 Split3)
Result.Push(Split2 Perm)
}
Return, Result
}
Recursion is a very powerful technique, but this one calls itself from inside a nested loop, and is too slow for my anagrams script that I was working on.
I could use Permutations() on up to 8 letters input comfortably (8! = 40,320), on 9 letters input (362,880) it is painfully slow.
Performance on 10 letters input (3,628,800) was unacceptable for my purpose.
However, the function may still be useful for other scripts. Enjoy
EDIT: removed a surplus line of code
more edits: I changed all occurrences of Permutation() to Permutations() to match the name of the function in the post.