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

前端 未结 8 2075
遥遥无期
遥遥无期 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
    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' ]

    0 讨论(0)
  • 2020-11-28 10:55
    <pre>
    <script>
    
    var count = 0;
    var duplicate = false;
    
    function FindAllPermutations(str, index) {
        for (var i = index; i < str.length; i++) {
            var newstr;
    
            if (index == i) newstr = str;
                else newstr = SwapLetters(str, index, i);
    
            if (!duplicate) {
                count++;
                document.write(newstr + "\n");
                if (i == index) duplicate = true;
            } else if (i != index) duplicate = false;
    
            FindAllPermutations(newstr, index + 1);
          }
      }
    
    function SwapLetters(str, index1, index2) {
        if (index1 == index2) return str;
        str = str.split("");
        var temp = str[index1];
        str[index1] = str[index2];
        str[index2] = temp;
        return str.join("");
    }
    
    FindAllPermutations("ABCD", 0); // will output all 24 permutations with no duplicates
    document.write("Count: " + count);
    
    </script>
    
    0 讨论(0)
提交回复
热议问题