【问题标题】:Derive every possible combination of elements in array导出数组中所有可能的元素组合
【发布时间】:2023-03-02 23:40:02
【问题描述】:

给定一个数组和一个长度,我想推导出特定长度的每个可能的元素组合(非重复)。

所以给定一个数组:

arr = ['a','b','c','d']

并且长度为3,我在一个输出二维数组的函数之后,如下所示:

result = [
    ['a','b','c'],
    ['b','c','a'],
    ['c','a','b'],
    . . . etc.
]

我已经尝试过解决这个问题并且遇到了很多困难。

【问题讨论】:

    标签: javascript arrays algorithm sorting combinations


    【解决方案1】:

    以下代码使用蛮力方法。它生成所需长度的每个组合的每个排列。排列会根据字典检查以避免在结果中重复。

    function makePermutations(data, length) {
      var current = new Array(length), used = new Array(length),
          seen = {}, result = [];
      function permute(pos) {
        if (pos == length) {      // Do we have a complete combination?
          if (!seen[current]) {   // Check whether we've seen it before.
            seen[current] = true; // If not, save it.
            result.push(current.slice());
          }
          return;
        }
        for (var i = 0; i < data.length; ++i) {
          if (!used[i]) {         // Have we used this element before?
            used[i] = true;       // If not, insert it and recurse.
            current[pos] = data[i];
            permute(pos+1);
            used[i] = false;      // Reset after the recursive call.
          }
        }
      }
      permute(0);
      return result;
    }
    
    var permutations = makePermutations(['a', 'a', 'b', 'b'], 3);
    for (var i = 0; i < permutations.length; ++i) {
      document.write('['+permutations[i].join(', ')+']<br />');
    }

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-28
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-01-25
      相关资源
      最近更新 更多