JavaScript生成所有组合

时间:2017-01-05 08:01:16

标签: javascript arrays

我有以下问题。 我有一些词(比方说3):word1 word2 word3,所有这些都用空格分隔,我想生成所有组合(3!表示6)像 word1 word2 word3 ... word2 word1 word3 ... word2 word3 word1 ... word3 word2 word1 ... word3 word1 word2 ... word1 word3 word2 ... 你能帮助我使用适用于任意数量单词的通用代码吗?

1 个答案:

答案 0 :(得分:0)

您可以使用"Permutations in JavaScript?"提供的解决方案之一。您只需将字符串拆分为单词,然后将单词连接回每个排列的字符串。

ES6演示:

function* permute(permutation) {
  var length = permutation.length,
      c = Array(length).fill(0),
      i = 1;

  yield permutation;
  while (i < length) {
    if (c[i] < i) {
      var k = i % 2 && c[i];
      [permutation[i], permutation[k]] = [permutation[k], permutation[i]];
      ++c[i];
      i = 1;
      yield permutation;
    } else {
      c[i++] = 0;
    }
  }
}

// sample input:
var s = 'this is a test';

for (var words of permute(s.split(/\s+/))) {
    console.log(words.join(' '));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }