试图在Javascript中实现this(马克回答)重叠区间算法,但我无法使它工作。实现算法来检查Javascript中的重叠区间算法
我想查看一个JSON数据结构中的值,选取代表行的x1-x2坐标的起始停止值。我一个接一个地添加新行,我想知道何时添加新行会导致行重叠。
我得到的错误是,它总是打印“没有重叠”,当有明显的重叠。
这是我的代码至今:
var
data = [],
json = [
{
"start" : 100,
"stop" : 800
},
{
"start" : 900,
"stop" : 1200
},
{
"start" : 200,
"stop" : 600
}
],
sortInterval, checkOverlappingInterval;
sortInterval = function (value) {
//Sorts a list with lower numbers first and end point come before
//starting points on ties
value.sort(function (a,b){
var aSplit = a.split("_"),
bSplit = b.split("_");
if (aSplit[0] * 1 > bSplit[0] * 1){
return 1;
}
if (aSplit[0] * 1 < bSplit[0] * 1) {
return -1;
} else {
if (aSplit[1] > bSplit[1]) {
return 1;
} else {
return -1;
}
}
});
};
checkOverlappingInterval = function(value){
//Return true if there are overlapps
var inInterval = false;
value.forEach(function(v) {
if (v.charAt(v.length-1) === "S"){
if(inInterval){
return true;
}
else {
inInterval = true;
}
}
else {
inInterval = false;
}
});
//return true;
return false;
};
json.forEach(function (value) {
//Push the new values to interval array and sort the array
data.push(value.start + "_S");
data.push(value.stop + "_E");
sortInterval(data);
//Check to see if the new line caused an overlapping line
//If it did increase y and clear out data
if (checkOverlappingInterval(data)){
console.log("overlaps");
}
//If it did not print line
else {
console.log("no overlaps");
}
});
哪个算法?答案似乎提出了多个不同的答案。 – Bergi
最高投票来自marcog – user3748315