Prefix sums (Creating an array with increasing sum) with Recursion in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Consider the following array of numbers −

const arr = [10, 5, 6, 12, 7, 1];

The sum of its consecutive elements taking one less element in every go will be −

[10, 5, 6, 12, 7, 1] = 10 + 5 + 6 + 12 + 7 + 1 = 41;
[5, 6, 12, 7, 1] = 5 + 6 + 12 + 7 + 1 = 31;
[6, 12, 7, 1] = 6 + 12 + 7 + 1 = 26;
[12, 7, 1] = 12 + 7 + 1 = 20;
[7, 1] = 7 + 1 = 8;
[1] = 1 = 1;

So, the final output should be an array like this −

[ 41, 31, 26, 20, 8, 1 ]

We are required to write a function that takes in one such array and returns the partialSum array back as illustrated in the example above.

Approach 1: Using map() and reduce() together

The idea here is simple, since we are required to return one particular element for each and every element in the array, we can use the Array.prototype.map() method which does exactly this for us.

And if we make the map() method to return the reduced sum of the required elements by comparing the particular indices, we will get the work done.

So, here is the code for doing this −

const arr = [10, 5, 6, 12, 7, 1];
const partSum = arr.map((item, index) => {
   return arr.reduce((acc, val, ind) => {
      return ind >= index ? acc+val : acc;
   }, 0);
});
console.log(partSum);

Approach 2: Using recursive functions

Here we will make use of two recursive functions,

  • First is sumRecursively(arr, start) which returns the sum of the elements of arr from the index start till the very end.

  • Second is partSumRecursively() that recursively concatenates the required sum into an array and when we reach the end of the array, it returns the concatenated array.

The code for doing this will be −

Example

const arr = [10, 5, 6, 12, 7, 1];
const sumRecursively = (arr, start = 0, res = 0) => {
   if(start < arr.length){
      return sumRecursively(arr, start+1, res+arr[start]);
   };
   return res;
};
const partSumRecursively = (arr, partSum = [], start = 0, end =
arr.length-1) => {
   if(start <= end){
      return partSumRecursively(arr, partSum.concat(sumRecursively(arr,
      start)), ++start, end);
   };
   return partSum;
};
console.log(partSumRecursively(arr));

Output

The output in the console for both of the methods will be −

[ 41, 31, 26, 20, 8, 1 ]
raja
Published on 20-Aug-2020 10:06:22
Advertisements