实现在Javascript中检查重叠间隔的算法
Implementing algorithm to check for overlapping intervals in Javascript
尝试在Javascript中实现这个(marcog的答案)重叠间隔算法,但我不能让它工作。
我想检查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");
}
});
两个错误:
- 在奇偶校验的情况下,你忘了从你的compcompation函数中去掉
return 0
。参见JavaScript中的排序:每个比较函数都应该有一个"return 0"声明吗? - 您正在尝试从
forEach
回调到return true
。这将只从当前回调返回,而不是从checkOverlappingInterval
函数返回。使用every
/some
,或正常的for
循环代替。
我相信这应该能行:
1)按起始值
对json数组进行排序2)我肯定知道开始总是大于所有以前的开始,所以我唯一要检查的是,如果任何以前的停止大于当前的开始,我正在检查。我用for语句这样做,并将最大停止值保存在一个变量中。所以如果当前起始点大于我设置的最大值,它就会重叠
json = [
{
"start" : 100,
"stop" : 800
},
{
"start" : 900,
"stop" : 1200
},
{
"start" : 200,
"stop" : 600
},
{"start":700, "stop":800}
];
function checkOverlaps(arr){
arr=arr.slice(0);
arr.sort(function(a,b){return a.start-b.start});
var max=0;
for(var i=1;i<arr.length;i++){
max=arr[i-1].stop > max ? arr[i-1].stop : max;
if(arr[i].start < max){
console.log(arr[i],"overlaps");
}
}
}
checkOverlaps(json);
相关文章:
- 循环比赛位置算法
- javascript扫雷器floodfill算法不能正常工作
- HighCharts长标题文本在某些元素上重叠
- 如何检测重叠元素下的单击
- 停止较大单词的重叠
- Node JS中的排名系统算法
- 查找仅适用于原始图像的图像放大算法的名称
- 在数组的 2/3 上调用自身的排序算法
- FullCalendar:事件发生时阻止重叠.标题是一样的
- Luhn算法的实现
- 算法:从数组(javascript/angular)中按当前日期获取上一个和下一个事件
- 加速单纯形算法
- 在页脚处停止固定侧边栏-防止重叠
- JS图表和html表格重叠
- 最短路径算法js错误
- 用于查找重叠事件/时间的算法
- 用于将重叠事件相加的算法
- 实现在Javascript中检查重叠间隔的算法
- 随机算法&有效地放置100个圆圈,没有任何重叠
- 算法不使随机放置的对象重叠