在 JavaScript 中查找一组垂直线段中所有不相交的交点
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 9:16:17
我们有一组由 y1 和 y2 坐标定义的垂直区域,其中 y1 是每个区域的起点,y2 是终点。
我们的坐标系的原点是左上角,因此 y2 始终大于 y1。
这是一个示例 −
constregions = [ [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 ] ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

