【问题标题】:Recursive forEach() in javascriptjavascript中的递归forEach()
【发布时间】:2020-11-12 22:20:53
【问题描述】:

例如,我有一堆数字数组:

let a = [1,2,3];
let b = [4,5,7];
let c = [11,13,17]

我想创建一个函数,告诉我数组中的数字组合乘以不同数组中的数字会得到某个数字。以下是我到目前为止的代码:

// to get which combination of numbers result to 165
a.forEach(x=>{
    b.forEach(y=>{
        c.forEach(z=>{
        if(x*y*z==165){
            console.log(x,y,z)
        }
        })
    })
})

我想创建一个函数,它可以输入一组数字数组,例如:[[1,2],[2,5,],[7,11],[13,17]],并返回数字组合,当它们相乘时,可以得到某个数字。

【问题讨论】:

标签: javascript arrays recursion math multiplication


【解决方案1】:

这是一个递归函数,它接受一个输入数字和一个数字数组数组。它通过第一个数字数组进行处理,找到任何可能的除数,如果是,则使用除法输入和数组的余额递归调用自己,以查看该对值中是否有任何除数。如果是这样,则将它们附加到当前除数以产生结果:

const findDivisors = (num, arrs) => {
  let result = [];
  if (arrs.length == 1) {
    return arrs[0].filter(n => n == num);
  }
  arrs[0].forEach(n => {
    if (num % n === 0) {
      findDivisors(num / n, arrs.slice(1)).forEach(r => result.push([n].concat(r)));
    }
  });
  return result;
}

let a = [1, 2, 3];
let b = [4, 5, 7];
let c = [11, 13, 17];
console.log(findDivisors(165, [a, b, c]));
console.log(findDivisors(136, [a, b, c]));

【讨论】:

    【解决方案2】:

    这表达了与尼克的答案相同的算法,但以非常不同的风格编写:

    const findDivisors = (t, [ns, ...nss]) =>
      nss .length == 0
        ? ns .filter (n => n == t) .map (n => [n])
        : ns .flatMap (n => t % n == 0 ? findDivisors (t / n, nss) .map (ns => [n, ...ns]) : [])
    
    const ns = [
      [1, 2, 3, 5, 6, 9],
      [2, 3, 4, 8, 12],
      [3, 5, 9, 12, 16, 18]
    ]
    
    console .log (findDivisors (100, ns))
    console .log (findDivisors (144, ns))
    console .log (findDivisors (240, ns))
    .as-console-wrapper {max-height: 100% !important; top: 0}

    我更喜欢使用表达式而不是语句。但据我所知,除了风格问题之外,它与尼克的答案相比没有任何优势或劣势。

    处理空数组的可能性可能会更好,这可能看起来像:

    const findDivisors = (t, [ns, ...nss]) =>
      ns == undefined
        ? []
      : nss .length == 0
        ? ns .filter (n => n == t) .map (n => [n])
        : ns .flatMap (n => t % n == 0 ? findDivisors (t / n, nss) .map (ns => [n, ...ns]) : [])
    

    【讨论】:

      猜你喜欢
      • 2021-07-29
      • 2018-04-22
      • 2020-04-24
      • 1970-01-01
      • 2023-04-02
      • 2021-10-20
      • 1970-01-01
      • 2015-05-01
      • 2012-09-29
      相关资源
      最近更新 更多