試圖在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