Find the sum of array element pairs by recursively consolidating them until only a single index remains.
EXAMPLES:
[1, 2, 3, 4, 5] => 48
Explanation:
- The next array would be [3, 5, 7, 9] because [1+2, 2+3, 3+4, 4+5]
- The next array would be [8, 12, 16] because [3+5, 5+7, 7+9]
- The next array would be [20, 28] because [8+12, 12+16]
- The final answer would be [48] because [20+28] and there are no more operands to add
I have implemented a solution for this problem using recursion, but I feel like there might be an easier approach. I'm trying to grasp the concept of recursion and how we determine the arguments passed into recursive calls. Can someone explain why we use (n - 1) or (n + 1) in our recursive calls and how we decide which one to use? I am also confused about passing arguments when returning from helper functions.
function reduceSum(input) {
function simplify(input, index) {
if (index === 1) {
return input[0];
}
if (index === 0) {
return 0;
}
for (let i = 0; i < input.length; i++) {
input[i] += input[i + 1];
}
return simplify(input, index - 1);
}
return simplify(input, input.length);
}
console.log(reduceSum([1, 2, 3, 4]) == 20)
console.log(reduceSum([5]) == 5)
console.log(reduceSum([]) == 0)
console.log(reduceSum([1, 3, 5]) == 12)
console.log(reduceSum([-5, 5]) == 0)
console.log(reduceSum([-5, 5, -5, 5]) == 0)
console.log(reduceSum([-5, 5, 5, -5]) == 20)