【问题标题】:Generating all combinations of elements in a single array (for cominations of N elements)在单个数组中生成所有元素组合(对于 N 个元素的组合)
【发布时间】:2021-12-06 00:16:06
【问题描述】:

我正在尝试构建/查找一个函数,它将为我提供 N 个元素的所有组合。

The solution 下面给出了对(即 2 个元素)的答案。

我想对其进行参数化,以便我可以定义组合元素的数量(例如 3 个元素 => ['one', 'two', 'three'], ['one', 'two', 'four'], ... 、4 个元素等。

(如果您能告诉我我要查找的名称(笛卡尔积?),将获得互联网积分奖励!)

var array = ['one', 'two', 'three', 'four', 'five']

// get pairs
var result = array => array.flatMap((v, i) => array.slice(i+1).map( w => [v, w] ));

console.log(result(array))

// output:
// [
//  ["one", "two"],
//  ["one", "three"],
//  ["one", "four"],
//  ["one", "five"],
//  ["two", "three"],
//  ["two", "four"],
//  ["two", "five"],
//  ["three", "four"],
//  ["three", "five"],
//  ["four", "five"]
// ]

【问题讨论】:

标签: javascript arrays cartesian-product


【解决方案1】:

解决办法是

var array = ['one', 'two', 'three', 'four', 'five']

var combine = function(a, min) {
    var fn = function(n, src, got, all) {
        if (n == 0) {
            if (got.length > 0) {
                all[all.length] = got;
            }
            return;
        }
        for (var j = 0; j < src.length; j++) {
            fn(n - 1, src.slice(j + 1), got.concat([src[j]]), all);
        }
        return;
    }
    var all = [];
    for (var i = min; i < a.length; i++) {
        fn(i, a, [], all);
    }
    all.push(a);
    return all;
}

console.log(combine(array, 2))

【讨论】:

  • 很好的答案!一个问题:无论如何将其限制为min 值?例如combine(array, 3).filter(x =&gt; x.length === 3)(而不是计算所有组合> N)
  • min 是最小计数组合的计数。
  • 谢谢,这是有道理的。我想我只需要 N,而不是 N、N+1、N+2 等。有没有办法可以设置“最大值”?
  • 如果您能对您的解决方案的工作原理提供一些解释,那就太好了! (例如内联 cmets?)
【解决方案2】:

我认为这是您的解决方案。

/** 
 * Usage Example:
 * 
 * console.log(combination(['A', 'B', 'C', 'D'], 2, true)); // [[ 'A','A' ], [ 'A', 'B' ]...] (16 items)
 * console.log(combination(['A', 'B', 'C', 'D'])); // [['A', 'A', 'A', 'B' ],.....,['A'],] (340 items)
 * console.log(comination(4, 2)); // all posible values [[ 0 ], [ 1 ], [ 2 ], [ 3 ], [ 0, 0 ], [ 0, 1 ], [ 0, 2 ]...] (20 items)
 */
function combination(item, n) {
  const filter = typeof n !=='undefined';
  n = n ? n : item.length;
  const result = [];
  const isArray = item.constructor.name === 'Array';

  const pow = (x, n, m = []) => {
    if (n > 0) {
      for (var i = 0; i < 4; i++) {
        const value = pow(x, n - 1, [...m, isArray ? item[i] : i]);
        result.push(value);
      }
    }
    return m;
  }
  pow(isArray ? item.length : item, n);

  return filter ? result.filter(item => item.length == n) : result;
}

console.log("#####first sample: ", combination(['A', 'B', 'C', 'D'], 2)); // with filter
console.log("#####second sample: ", combination(['A', 'B', 'C', 'D'])); // without filter
console.log("#####third sample: ", combination(4, 2)); // just number

【讨论】:

  • 谢谢@Danilo,很好的回答。一个问题,它显示重复...例如:[["A", "A"], ["B", "B"], ["C", "C"]。你能排除他们吗?
  • 如果您能对您的解决方案的工作原理提供一些解释,那就太好了! (例如内联 cmets?)
猜你喜欢
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多