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

前端 未结 8 2155
遥遥无期
遥遥无期 2020-11-28 10:28

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 give

8条回答
  •  天涯浪人
    2020-11-28 10:54

    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.

提交回复
热议问题