Ant's Ant's - 1 month ago 8
Javascript Question

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

I'm a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a given string.

For example, given the input:

the


Desired output:

the
teh
eht
eth
het
hte

Answer

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.

Comments