获取某些字符 JavaScript 的所有可能组合

get all possible combinations of some characters javascript

本文关键字:有可能 组合 JavaScript 字符 获取      更新时间:2023-09-26

所以如果 a 有 A, B, C,我想创建一些长度为 4 的字符串

所以输出将是

AAAA
AAAB
AAAC
AABA
AABB
AABC
ABAB
....
CCCC

有一些评论,所以你可以理解这一点。感谢 http://www.walmik.com/2013/03/rearrange-letters-of-a-word/

function permutate(theWord){
      //Array to store the generated words
      var words = [];
      /**
       * Recursive function to split a string and rearrange 
       * it's characters and then join the results
       */
      function rearrange(str, prefix) {
        var i, singleChar, balanceStr, word;
        //The first time round, prefix will be empty
        prefix = prefix || '';
        //Loop over the str to separate each single character
        for(i = 0; i < str.length; i++) {
          singleChar = str[i];
          balanceStr = str.slice(0, i) + str.slice(i+1);
          //join the prefix with each of the combinations
          word = prefix + singleChar + balanceStr;
          //Inject this word only if it does not exist
          if(words.indexOf(word) < 0) words.push(word);
          //Recursively call this function in case there are balance characters
          if(balanceStr.length > 1) rearrange(balanceStr, prefix + singleChar);
        }
      }
      //kick start recursion
      rearrange(theWord);
      return words;
    }
    var permutatedWord = permutate('goal');
    console.log(permutatedWords);