- Related Questions & Answers
- Count BST subtrees that lie in given range in C++
- Print missing elements that lie in range 0 – 99
- Finding sum of all numbers within a range in JavaScript
- Count BST nodes that lie in a given range in C++
- Counting prime numbers that reduce to 1 within a range using JavaScript
- Prime numbers within a range in JavaScript
- Armstrong number within a range in JavaScript
- Find a range that covers all the elements of given N ranges in C++
- Converting a comma separated string to separate arrays within an object JavaScript
- Generating desired pairs within a range using JavaScript
- Finding sequential digit numbers within a range in JavaScript
- Find pairs with given sum such that pair elements lie in different BSTs in Python
- PHP program to find the sum of odd numbers within a given range
- Summing cubes of natural numbers within a range in JavaScript
- Sum identical elements within one array in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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));

And the output in the console will be −

11 122

Advertisements