Is there any pre-built method for finding all permutations of a given string in JavaScript?

//string permutation

function permutation(start, string) {

    //base case
    if ( string.length == 1 ) {
        return [ start + string ];
    } else {

        var returnResult = [];
        for (var i=0; i < string.length; i++) {
            var result = permutation (string[i], string.substr(0, i) + string.substr(i+1));
            for (var j=0; j<result.length; j++) {
                returnResult.push(start + result[j]);
            }
        }

        return returnResult;
    }
}

permutation('','123') will return

["123", "132", "213", "231", "312", "321"]


No pre-built, but writing such function is possible.. here is one relatively simple way using two functions:

function FindAllPermutations(str, index, buffer) {
    if (typeof str == "string")
        str = str.split("");
    if (typeof index == "undefined")
        index = 0;
    if (typeof buffer == "undefined")
        buffer = [];
    if (index >= str.length)
        return buffer;
    for (var i = index; i < str.length; i++)
        buffer.push(ToggleLetters(str, index, i));
    return FindAllPermutations(str, index + 1, buffer);
}

function ToggleLetters(str, index1, index2) {
    if (index1 != index2) {
        var temp = str[index1];
        str[index1] = str[index2];
        str[index2] = temp;
    }
    return str.join("");
}

Usage:

var arrAllPermutations = FindAllPermutations("the");

Live test case: http://jsfiddle.net/yahavbr/X79vz/1/

This is just basic implementation, it won't remove duplicates and has no optimization. However for small strings you won't have any problem, add time measure like in the above test case and see what's your reasonable limit.


function permutations(str){
  if (str.length === 1)
      return str;
  var permut = [];
  for (var i=0; i<str.length; i++){
      var s = str[0];
      var _new =  permutations(str.slice(1, str.length));
      for(var j=0; j<_new.length; j++)
          permut.push(s + _new[j]);
      str = str.substr(1, str.length -1) + s;
  }
  return permut; }

permutations('the');
//output returns:[ 'the', 'teh', 'het', 'hte', 'eth', 'eht' ]

Tags:

Javascript