Created
March 30, 2021 13:52
-
-
Save AidaP1/7f0065f03a95f90c0ed3720ea8bf3219 to your computer and use it in GitHub Desktop.
Codewars challenge to find the difference between numbers in an array, after deduplicating
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Description below | |
function sumIntervals(intervals){ | |
const sortedArr = intervals.map((e) => e).sort((a,b) => a[0] - b[0]); | |
//console.log(sortedArr) | |
const refArr = sortedArr.reduce(function (acc,curr,index,array) { | |
let anterior = array[index - 1]; | |
if(anterior !== undefined) { | |
if(curr[0] < acc[acc.length - 1] && curr[1] > acc[acc.length - 1]) { | |
let newArr = [acc[acc.length -1],curr[1]]; | |
acc.push(...newArr); | |
} else if (curr[0] > acc[acc.length -1]) { | |
acc.push(...curr) | |
} | |
} else { | |
acc.push(...curr) | |
} | |
return acc | |
}) | |
//console.log(refArr) | |
return refArr.reduce((a,b) => b - a) | |
} | |
/* | |
Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. | |
Intervals | |
Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. | |
Overlapping Intervals | |
List containing overlapping intervals: | |
[ | |
[1,4], | |
[7, 10], | |
[3, 5] | |
] | |
The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment