I am trying to solve “A very big sum” challenge on Hacker Rank: https://www.hackerrank.com/challenges/a-very-big-sum/problem
In there I have to sum all the numbers in the array given so I came up with two solutions:
First solution
JavaScript
x
7
1
function aVeryBigSum(ar){
2
let sum = 0;
3
for(let i = 0; i < ar.length; i++){
4
sum += i;
5
}
6
}
7
Second Solution
JavaScript
1
6
1
function(ar){
2
let sum = ar.reduce((accumulator, currentValue) => {
3
accumulator + currentValue;
4
});
5
}
6
But none of them work and I don´t know why, I am thiniking maybe I am not writing it as Hacker Rank wants me to but I am not sure
Advertisement
Answer
sum += i;
should be sum += ar[i];
Also return sum
JavaScript
1
8
1
function aVeryBigSum(ar){
2
let sum = 0;
3
for(let i = 0; i < ar.length; i++){
4
sum += ar[i];
5
}
6
return sum;
7
}
8
Also reducer function should be like
JavaScript
1
5
1
function a(ar){
2
let sum = (accumulator, currentValue) => accumulator + currentValue;
3
return ar.reduce(sum);
4
}
5