【问题标题】:JavaScript generates all combination [duplicate]JavaScript生成所有组合[重复]
【发布时间】:2017-05-19 16:42:07
【问题描述】:

我有以下问题。 我有一些单词(比如说 3 个): word1 word2 word3,它们都用空格分隔,我想生成所有组合(3!这意味着 6),比如 单词1 单词2 单词3... 字2字1字3... 单词2 单词3 单词1... 单词3 单词2 单词1... 单词3 单词1 单词2... 单词1 单词3 单词2... 你能帮我提供一个适用于任意数量单词的通用代码吗?

【问题讨论】:

标签: javascript arrays


【解决方案1】:

您可以使用提供给"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; }

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多