Skip to content

Instantly share code, notes, and snippets.

@ironboy
Created August 30, 2015 21:04
Show Gist options
  • Select an option

  • Save ironboy/ef85939d797dd7d3457e to your computer and use it in GitHub Desktop.

Select an option

Save ironboy/ef85939d797dd7d3457e to your computer and use it in GitHub Desktop.
/*
Solution to:
https://blog.svpino.com/2015/05/17/programming-challenge-merging-overlapping-intervals
*/
function combineOverlappingIntervals(intervals){
var overlapping = [], newOnes = [];
// Compare each interval with every other interval
intervals.forEach(function(x){
intervals.forEach(function(y){
// Don't compare with itself
if(x===y){return;}
// Check if overlap (easier math to calculate when
// not overlapping, so use this and negate)
var overlap = !(x[0] > y[1] || y[0] > x[1]);
// If overlapping and not detected already
if(overlap && overlapping.indexOf(x) < 0){
// Store overlapping intervals
overlapping.push(x,y);
// Create new interval
newOnes.push([Math.min(x[0],y[0]),Math.max(x[1],y[1])]);
}
});
});
// Loop through original intervals, find those
// that aren't overlapping and include them too
intervals.forEach(function(x){
overlapping.indexOf(x) < 0 && newOnes.push(x);
});
return newOnes;
}
// Test
combineOverlappingIntervals([
[1,7],
[2,8],
[13,15],
[14,16],
[28,35]
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment