简体   繁体   English

CodeWars 上的 javascript 挑战:我的解决方案有什么问题?

[英]javascript challenge on CodeWars: what's wrong with my solution?

I'm fairly new to programming and javascript, and recently started working on CodeWars challenges.我对编程和 javascript 还很陌生,最近开始着手应对 CodeWars 挑战。 I wasn't able to pass the challange below with my solution, and even when I compared against solutions from other users, I couldn't find what the issue was with mine.我的解决方案无法通过下面的挑战,即使与其他用户的解决方案进行比较时,我也找不到我的问题所在。

Challenge:挑战:

"Complete the squareSum/square_sum/SquareSum method so that it squares each number passed into it and then sums the results together. “完成 squareSum/square_sum/SquareSum 方法,以便它对传入的每个数字进行平方,然后将结果相加。

For example: squareSum([1, 2, 2]);例如: squareSum([1, 2, 2]); // should return 9" // 应该返回 9"

My code:我的代码:

function squareSum(numbers){
  var sqNum = numbers.map(num=>num*num);
  var addNum = sqNum.reduce((acc,curr)=> acc + curr);
  return addNum
};

Am I missing something?我错过了什么吗?

function squareSum(numbers){
    return numbers.reduce((acc,curr)=> acc + curr * cur, 0);
}

Avoid the full copy with map.避免带有地图的完整副本。 You will most likely hit either the run time or memory limit for the test cases with large arrays.对于大型数组的测试用例,您很可能会达到运行时间或内存限制。

CodeWars is not only about correct implementation, but also about reasonable efficiency. CodeWars 不仅关乎正确的实现,而且关乎合理的效率。

This solution per se is working ok, I have tried at codepen.这个解决方案本身工作正常,我已经在 codepen 上尝试过。 It has to be with the way you present your answer.它必须与您提出答案的方式有关。 I don't know how exactly codewars works, but keep in mind that you are not calling the function squareSum anywhere.我不知道 codewars 究竟是如何工作的,但请记住,您不会在任何地方调用函数squareSum And when you do it, remember to pass the numbers within an array.当你这样做时,记得在数组中传递数字。

function squareSum(numbers){
  var sqNum = numbers.map(num=>num*num);
  var addNum = sqNum.reduce((acc,curr)=> acc + curr);
  console.log( addNum )
};

squareSum([1, 2, 2]);

This works just fine这工作得很好

This is my solution the code wars challenge...Was well

 function square_sum(numbers) {
    return numbers.reduce(function(sum, x) {
      return (x * x) + sum;
    }, 0)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM