在 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