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.
There is already plenty of good solutions here, but I would like to share how I solved this problem on my own and hope that this might be helpful for somebody who would also like to derive his own solution.
After some pondering about the problem I have come up with two following conclusions:
L
of sizen
there will be equal number of solutions starting with L1, L2 ... Ln elements of the list. Since in total there aren!
permutations of the list of sizen
, we getn! / n = (n-1)!
permutations in each group.[a,b]
and[b,a]
.Using these two simple ideas I have derived the following algorithm:
Here is how I implemented this in C#:
Here is a recursive solution in PHP. WhirlWind's post accurately describes the logic. It's worth mentioning that generating all permutations runs in factorial time, so it might be a good idea to use an iterative approach instead.
The strDiff function takes two strings,
s1
ands2
, and returns a new string with everything ins1
without elements ins2
(duplicates matter). So,strDiff('finish','i')
=>'fnish'
(the second 'i' is not removed).Here is an algorithm in Python that works by in place on an array:
You can try the code out for yourself here: http://repl.it/J9v
If anyone wonders how to be done in permutation in javascript.
Idea/pseudocode
for example. 'a'+ permute(bc). permute of bc would be bc & cb. Now add these two will give abc, acb. similarly, pick b + permute (ac) will provice bac, bca...and keep going.
now look at the code
Take your time to understand this. I got this code from (pertumation in JavaScript)
Java version
E.g.
output:
in PHP