【问题标题】:Generating full (all sizes) combinations of arrays生成数组的完整(所有大小)组合
【发布时间】:2019-05-16 07:02:03
【问题描述】:

如何生成多个数组的完全组合?

const source = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"] ];
const result = combination(source);

需要结果,如笛卡尔积,但有各种尺寸的组合:

["a"]
["a", "d"]
["a", "d", "g"]
...
["b"]
...
["b", "f", "i"]
...
["i"]

【问题讨论】:

  • 你尝试过什么伙伴?

标签: javascript combinations cartesian-product


【解决方案1】:

这个怎么样:

function cartesianProduct(arrArr) {
  if (arrArr.length === 0) return [];

  const [firstArr, ...restArrs] = arrArr;
  const partialProducts = cartesianProduct(restArrs || []);

  let ret = firstArr.map(elem => [elem]);
  ret = ret.concat(partialProducts);
  ret = ret.concat(partialProducts.reduce((acc, product) => {
    return acc.concat(firstArr.map(elem => [elem].concat(product)));
  }, []));

  return ret;
}

【讨论】:

  • 谢谢,正是需要的!
猜你喜欢
  • 1970-01-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多