Find all disjointed intersections in a set of vertical line segments in JavaScript


We have a set of vertical regions defined by y1 and y2 coordinates, where y1 is the starting point and y2 is the ending point of each region.

The origin of our coordinates system is the top-left corner, so y2 is always greater than y1.

This is an example −

const regions = [
   [10, 100],
   [50, 120],
   [60, 180],
   [140, 220]
];

We are required to write a JavaScript function that takes in one such region array as the first argument and a number as the second argument.

We would like to find out all disjointed intersections greater than a certain size, (specified by the second argument of the function).

Let’s say, for example, 20 units.

Then the output for the above array should look like −

const output = [
   [60, 100],
   [140, 180]
];

We could use a simplified algorithm and use across the product for searching for overlapping items.

Then get the common parts by iterating and filter only unknown matches.

Example

The code for this will be −

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));

Output

And the output in the console will be −

[ [ 60, 100 ], [ 140, 180 ] ]

Updated on: 24-Nov-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements