在 JavaScript 中查找一组垂直线段中所有不相交的交集
我们有一组由 y1 和 y2 坐标定义的垂直区域,其中 y1 是每个区域的起点,y2 是每个区域的终点。
我们的坐标系原点位于左上角,因此 y2 始终大于 y1。
这是一个示例 -
const regions = [ [10, 100], [50, 120], [60, 180], [140, 220] ];
我们需要编写一个 JavaScript 函数,该函数将一个这样的区域数组作为第一个参数,并将一个数字作为第二个参数。
我们希望找出所有大于特定大小(由函数的第二个参数指定)的不相交的交集。
例如,假设为 20 个单位。
那么上面数组的输出应该如下所示 -
const output = [ [60, 100], [140, 180] ];
我们可以使用一个简化的算法,并使用跨积来搜索重叠的项目。
然后通过迭代获取公共部分,并仅过滤未知匹配项。
示例
代码如下 -
const regions = [
[10, 100],
[50, 120],
[60, 180],
[140, 220]
];
const getIntersections = (arr,num) => {
let disjoint, res;
return arr.reduce((acc,val,ind,array) => {
if (val.used){
return acc;
};
res = array.map((el, index) => array[(ind + index) % array.length]) .reduce((s,e) => {
disjoint = [Math.max(s[0],e[0]), Math.min(s[1],e[1])];
return disjoint[0] < disjoint[1] ? (e.used = true, disjoint) : s;
});
res[1] - res[0] > num && acc.push(res);
return acc;
},[]);
}
console.log(getIntersections(regions, 20));输出
控制台中的输出将如下所示 -
[ [ 60, 100 ], [ 140, 180 ] ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP