Generate permutations of JavaScript array -


i have array of n different elements in javascript, know there n! possible ways order these elements. want know what's effective (fastest) algorithm generate possible orderings of array?

i have 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 = "";          (var = 0; < 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 works, guess swapping every item combinations bit expensive memory wise, thought way of doing focusing on indexes of array , getting permutations of numbers, i'm wondering if there's way of computing of them without having switch elements within array? guess recursively possible of them, need so.

so example if have:

arrcities = ["sidney", "melbourne", "queenstown"]; 

i want output 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'm reading this: http://en.wikipedia.org/wiki/permutation#algorithms_to_generate_permutations

but wikipedia has never been @ explaining. don't understand of it, have math level isn't best.

using heap's method (you can find in paper wikipedia article links to), can generate permutations of n elements runtime complexity in o(n!) , space complexity in o(n). algorithm based on swapping elements. afaik fast gets, there no faster method calculate permutations.

for implementation , examples, please have at recent answer @ related question "permutations in javascript".


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo