Given an array of length n, consolidate the sum created by adding index pairs until there's only a single index.
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 not enough operands to add
This is the solution I came up with but I feel like there's a simpler way to achieve the same solution. I'm trying to understand recursion but I need some explanation on why when we call our stacks, we do it from the (n - 1) or from the (n + 1) to reach our base cases and how do we know which one to use? I don't understand why we're using those passing arguments when we are returning our helper function.
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)
[-5, 5, 5, -5]and then do aconsole.log(input)after the for loop to see what happens toinput. For each recursive loop, the last index will be NaN, hence why the code is callingsimplify(input, index - 1). Tbh, this solution is much shorter than I would had come up with.