Algorithm to sum ranges that lie within another separate range in JavaScript


We have two sets of ranges; one is a single range of any length (R1) and the other is a set of ranges (R2) some or parts of which may or may not lie within the single range (R1).

We need to calculate the sum of the ranges in (R2) - whole or partial - that lie within the single range (R1).

const R1 = [20,40];
const R2 = [[14,22],[24,27],[31,35],[38,56]];

Result 

= 2+3+4+2 = 11
R1 = [120,356];
R2 = [[234,567]];

Result 

122

Example

Let us write the code −

const R1 = [20,40];
const R2 = [[14,22],[24,27],[31,35],[38,56]];
const R3 = [120,356];
const R4 = [[234,567]];
function sumRanges(range, values) {
   const [start, end] = range;
   const res = values.reduce((acc, val) => {
      const [left, right] = val;
      const ex1 = Math.min(right, end);
      const ex2 = Math.max(left, start);
      const diff = ex1 - ex2;
      return acc + Math.max(0, diff);
   }, 0);
   return res;
};
console.log(sumRanges(R1, R2));
console.log(sumRanges(R3, R4));

Output

And the output in the console will be −

11
122

Updated on: 20-Nov-2020

49 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements