Permutations in JavaScript? -


i'm trying write function following:

  • takes array of integers argument (e.g. [1,2,3,4])
  • creates array of possible permutations of [1,2,3,4], each permutation having length of 4

the function below (i found online) taking string argument, , returning permutations of string

i not figure out how modify make work array of integers, (i think has how of methods work differently on strings on integers, i'm not sure...)

var permarr = [], usedchars = []; function permute(input) {   var i, ch, chars = input.split("");   (i = 0; < chars.length; i++) {     ch = chars.splice(i, 1);     usedchars.push(ch);     if (chars.length == 0)       permarr[permarr.length] = usedchars.join("");     permute(chars.join(""));     chars.splice(i, 0, ch);     usedchars.pop();   }   return permarr }; 

note: i'm looking make function return arrays of integers, not array of strings.

i need solution in javascript. i've figured out how in python

if notice, code splits chars array prior permutation, remove join , split operation

var permarr = [],    usedchars = [];    function permute(input) {    var i, ch;    (i = 0; < input.length; i++) {      ch = input.splice(i, 1)[0];      usedchars.push(ch);      if (input.length == 0) {        permarr.push(usedchars.slice());      }      permute(input);      input.splice(i, 0, ch);      usedchars.pop();    }    return permarr  };      document.write(json.stringify(permute([5, 3, 7, 1])));


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -