【问题标题】:get all possible combinations of some characters javascript [duplicate]获取某些字符的所有可能组合javascript [重复]
【发布时间】:2014-12-13 06:25:56
【问题描述】:

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

所以输出将是

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

【问题讨论】:

  • 链接的重复问题不重复。在链接的问题中只允许唯一的字符组合,在这个问题中允许相同的字符重复。

标签: javascript


【解决方案1】:

有一些cmets,所以你可以理解这一点。感谢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);

【讨论】:

  • 谢谢,但我也需要带有重复字符的字符串,例如 BBAA
猜你喜欢
  • 2015-01-15
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
  • 2012-03-20
  • 1970-01-01
  • 2011-07-04
  • 1970-01-01
相关资源
最近更新 更多