【问题标题】:Returning true if sum of squared is greater than sum of cubed如果平方和大于立方和,则返回 true
【发布时间】:2021-03-15 19:50:22
【问题描述】:

这里有点菜鸟问题。

在 CodeWars 挑战中,我正在尝试为大于“b”的“a”的所有数组平方和返回 true。这是我目前所拥有的:

function arrayMadness(a, b) {
  
  a = a.reduce((ele, ele2) => {
    return (ele ** 2) + (ele2 ** 2);
});
  b = b.reduce((ele, ele2) => {
    return (ele *ele *ele) + (ele2 *ele2 * ele2);
});

  if (a > b) {
   return true;
   } else return false;
}

但是,我的一些测试仍然失败。谁能帮我看看我哪里出错了?

提前非常感谢! :)

附:这是挑战:https://www.codewars.com/kata/56ff6a70e1a63ccdfa0001b1/train/javascript

【问题讨论】:

  • 你能修正一下代码的缩进吗?很难阅读。

标签: javascript arrays boolean reduce


【解决方案1】:

代码答案在这里

function arrayMadness(a, b) {
  sumA = a.reduce((acc, currentEl) => {
    return acc + (currentEl ** 2);
  }, 0);
  sumB = b.reduce((acc, currentEl2) => {
    return acc + Math.pow(currentEl2, 3);
  }, 0);

  return (sumA > sumB) ? true : false;
}

说明:reduce 需要 4 个参数,您也可以将 initialValue 定义为额外参数,正如您在我的代码中逗号 '0' 之后看到的那样,其中 reduce 包括要计算的数组的第一个索引。 参考:reduce

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    相关资源
    最近更新 更多