Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cumulative total with restart upon reaching a limit with a condition

I have an array:

arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];

All the numbers are below ’10’. I want the cumulative total of the numbers. But with two conditions:

  1. upon reaching a total closest to ’10’ the last number that makes total to be less than or equal to ’10’ should be replaced with ’10’ AND
  2. the cumulative total starts from next number.

So, the output should be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

outputArr = [2, 6, 10, 10, 8, 10, 3, 10, 9, 10];

I have this code:

arr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
total = 0;
outputArr = [];
for (i = 0; i < arr.length; i++) {
  if (total + arr[i] <= 10) {
    total += arr[i];
    outputArr.push(total);
  } else {
    total = arr[i];
    outputArr.push(total);
  }
}
console.log(outputArr);

This code gives me this output:

outputArr = [2, 6, 9, 7, 8, 10, 3, 7, 9, 10]

Here, cumulative total and its restarting upon reaching 10 works fine.
But the problem as you see is:
before restarting, it can’t replace last item with 10.

Any help is much appreciated.

>Solution :

You could update the output array based on whether the cumulative sum is < 10 or == 10 or > 10

let input = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1],
    output = [],
    cumulative = 0;

for (let i = 0; i < input.length; i++) {
  cumulative += input[i];

  if (cumulative < 10) {
    output.push(cumulative)
  } else if (cumulative == 10) {
    output.push(10)
    cumulative = 0
  } else {
    output[i-1] = 10
    cumulative = input[i]
    output.push(cumulative)
  }
}

console.log(output)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading