I wrote a function called generateCombination, which takes an array of integer ranges as input and generates all possible non-overlapping combinations of events in the array. From this array you can extract the largest arrays of ranges, which are ranges that contain as many events as possible.
http://jsfiddle.net/nvYZ8/1/
var theArray = generateCombination([[0, 2], [2, 3], [4, 5], [0, 9], [2, 50]]); alert(JSON.stringify(theArray)); function generateCombination(theArray) { var theString = ""; var tempArray = new Array(); for (var i = 0; i < theArray.length; i++) { theString += "1"; } var maximumNumber = convertFromBaseToBase(theString, 2, 10); for (var k = 0; k <= maximumNumber; k++) { theString = convertFromBaseToBase(k + "", 10, 2); while(theString.length != theArray.length){ theString = "0" + theString; } var theResult = getArray(theArray, theString); if(theResult != false){ tempArray[tempArray.length] = JSON.stringify(theResult); } } return tempArray; } function getArray(theArray, theString){ var tempArray = new Array(); for(var i = 0; i < theArray.length; i++){ if(theString[i] == 1){ tempArray[tempArray.length] = theArray[i]; } } for (var i = 0; i < theArray.length; i++) { for (var j = i; j < theArray.length; j++) { if ((j != i) && (theString[i] == 1) && (theString[j] == 1)) { //check whether theArray[i] overlaps with theArray[j] var overlaps = rangesOverlap(theArray[i][0], theArray[i][1], theArray[j][0], theArray[j][1]); //if overlaps is true, break out of the current loop //otherwise, add theArray[j] to tempArray if(overlaps == true){ return false; } } } } return tempArray; } function convertFromBaseToBase(str, fromBase, toBase) { var num = parseInt(str, fromBase); return num.toString(toBase); } function rangesOverlap(x1, x2, y1, y2) { if (x1 <= y2 && y1 <= x2) { return true; } else { return false; } }
source share