【问题标题】:Write a generalized function that prints all combinations. No recursion [duplicate]编写一个打印所有组合的通用函数。没有递归[重复]
【发布时间】:2017-10-08 09:28:22
【问题描述】:

我想打印数组中每个数字的所有可能组合,并将所有组合存储在一个数组中。

到目前为止,我只使数组变平。

我知道我需要一个将数组作为参数然后返回所有可能组合的函数。

let array = [
  [0, 1, 8],
  [2, 3],
  [4, 5]
 ];

const allPossibleCombinations = function (array) {
  const combinations = [];
        return array.reduce((p,c) =>
          [...p, ...c] );
};

console.log(allPossibleCombinations(array))

但我需要这个结果

[ '0 2 4',
  '0 2 5',
  '0 3 4',
  '0 3 5',
  '1 2 4',
  '1 2 5',
  '1 3 4',
  '1 3 5',
  '8 2 4',
  '8 2 5',
  '8 3 4',
  '8 3 5' ]

【问题讨论】:

  • 三个嵌套的for循环怎么样?
  • this question上有几个非递归答案...
  • 递归有什么问题?

标签: javascript arrays


【解决方案1】:

可能不是最有效的解决方案,但这会产生所需的输出:

const [one, two, three] = [
  [0, 1, 8],
  [2, 3],
  [4, 5]
];
const output = [];

for (let i of one) {
   for (let j of two) {
      for (let h of three) {
         output.push([i, j, h]);
      }
   }
}

console.log(output);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    • 2020-12-05
    • 2013-05-05
    相关资源
    最近更新 更多