我们有两组范围;一个是任意长度(R1)的单个范围,另一个是一组范围(R2),其中某些或部分范围可能会或可能不会在单个范围(R1)内。
我们需要计算(R2)中的范围之和-整个或部分-处于单个范围(R1)之内。
const R1 = [20,40]; const R2 = [[14,22],[24,27],[31,35],[38,56]];
结果
= 2+3+4+2 = 11
R1 = [120,356]; R2 = [[234,567]];
结果
122
让我们写代码-
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));
输出结果
控制台中的输出将是-
11 122