Say I have a list of n elements, I know there are n! possible ways to order these elements. What is an algorithm to generate all possible orderings of this list? Example, I have list [a, b, c]. The algorithm would return [[a, b, c], [a, c, b,], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].
I'm reading this here http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
But Wikipedia has never been good at explaining. I don't understand much of it.
In the following Java solution we take advantage over the fact that Strings are immutable in order to avoid cloning the result-set upon every iteration.
The input will be a String, say "abc", and the output will be all the possible permutations:
Code:
Same approach can be applied to arrays (instead of a string):
Recursive always takes some mental effort to maintain. And for big numbers, factorial is easily huge and stack overflow will easily be a problem.
For small numbers (3 or 4, which is mostly encountered), multiple loops are quite simple and straight forward. It is unfortunate answers with loops didn't get voted up.
Let's start with enumeration (rather than permutation). Simply read the code as pseudo perl code.
Enumeration is more often encountered than permutation, but if permutation is needed, just add the conditions:
Now if you really need general method potentially for big lists, we can use radix method. First, consider the enumeration problem:
Radix increment is essentially number counting (in the base of number of list elements).
Now if you need permutaion, just add the checks inside the loop:
Edit: The above code should work, but for permutation, radix_increment could be wasteful. So if time is a practical concern, we have to change radix_increment into permute_inc:
Of course now this code is logically more complex, I'll leave for reader's exercise.
Here's an implementation for ColdFusion (requires CF10 because of the merge argument to ArrayAppend() ):
Based on KhanSharp's js solution above.
I have written this recursive solution in ANSI C. Each execution of the Permutate function provides one different permutation until all are completed. Global variables can also be used for variables fact and count.
Reference: Geeksforgeeks.org