- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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 ] ]

- Related Questions & Answers
- C++ program to find the number of triangles amongst horizontal and vertical line segments
- How do I find the intersection of two line segments in Matplotlib?
- How to find all subsets of a set in JavaScript?
- Program to find number of sets of k-non-overlapping line segments in Python
- Check if two line segments intersect
- Klee’s Algorithm (Length Of Union Of Segments of a line) in C++
- Legend with vertical line in matplotlib
- Maximum possible intersection by moving centers of line segments in C++
- Interval List Intersections in C++
- How to create a line chart using ggplot2 with a vertical line in R?
- Find all distinct subsets of a given set in C++
- How to create a vertical line with CSS?
- Find the Number of segments where all elements are greater than X using C++
- Number of Segments in a String in C++
- Set all list items on a single line with Bootstrap