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.
I know this a very very old and even off-topic in today's stackoverflow but I still wanted to contribute a friendly javascript answer for the simple reason that it runs in your browser.
I've also added the
debugger
directive breakpoint so you can step through the code (chrome required) to see how this algorithm works. Open up your dev console in chrome (F12
in windows orCMD + OPTION + I
on mac) and then click "Run code snippet". This implements the same exact algorithm that @WhirlWind presented in his answer.Your browser should pause execution at the
debugger
directive. UseF8
to continue code execution.Step through the code and see how it works!
This is a recursive code for java, the idea is to have a prefix that add the rest of the characters:
Example:
Input = "ABC"; Output:
ABC ACB BAC BCA CAB CBA
Here is an algorithm in R, in case anyone needs to avoid loading additional libraries like I had to.
Example usage:
I created this one. based on research too permutate(qwe, 0, qwe.length-1); Just so you know, you can do it with or without backtrack
Here is the code in Python to print all possible permutations of a list:
I have used a lexicographic order algorithm to get all possible permutations, but a recursive algorithm is more efficient. You can find the code for recursive algorithm here: Python recursion permutations
Bourne shell solution - in a total of four lines (without test for no param case):