我写了一个名为generateCombination的函数,它接受一个整数范围数组作为输入,并生成数组中所有可能的非重叠事件组合。从这个数组中,你可以提取包含最大事件数量的范围的最大数组。
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)) {
var overlaps = rangesOverlap(theArray[i][0], theArray[i][1], theArray[j][0], theArray[j][1]);
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;
}
}