I have an array of n different elements in javascript, I know there are n! possible ways to organize these elements. I want to find out what is the most efficient (fastest) algorithm for generating all possible orders of this array?
I have this code:
var swap = function(array, frstElm, scndElm) { var temp = array[frstElm]; array[frstElm] = array[scndElm]; array[scndElm] = temp; } var permutation = function(array, leftIndex, size) { var x; if(leftIndex === size) { temp = ""; for (var i = 0; i < array.length; i++) { temp += array[i] + " "; } console.log("---------------> " + temp); } else { for(x = leftIndex; x < size; x++) { swap(array, leftIndex, x); permutation(array, leftIndex + 1, size); swap(array, leftIndex, x); } } } arrCities = ["Sidney", "Melbourne", "Queenstown"]; permutation(arrCities, 0, arrCities.length);
And it works, but I think replacing each element to get combinations is a bit expensive memory, I thought a good way to do this is to just focus on the array indices and get all the permutations of the numbers, I wonder if there is a way to calculate everything from them without having to switch elements inside the array? I think that recursively you can get all of them, I need help for this.
So, for example, if I have:
arrCities = ["Sidney", "Melbourne", "Queenstown"];
I want the output to be:
[[012],[021],[102],[120],[201],[210]]
or
[[0,1,2], [0,2,1], [1,0,2], [1,2,0], [2,0,1], [2,1,0]]
I read this: http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
But Wikipedia never knew how to explain. I do not really understand it, I must say that my mathematical level is not the best.