Find intersection point of lines inside a section
Given N lines in two-dimensional space in y = mx + b form and a vertical section. We need to find out whether there is an intersection point inside the given section or not.
Examples:
In below diagram four lines are there,
L1 : y = x + 2
L2 : y = -x + 7
L3 : y = -3
L4 : y = 2x – 7
and vertical section is given from x = 2 to x = 4
We can see that in above diagram, the
intersection point of line L1 and L2
lies between the section.
We can solve this problem using sorting. First, we will calculate intersection point of each line with both the boundaries of vertical section and store that as a pair. We just need to store y-coordinates of intersections as a pair because x-coordinates are equal to boundary itself. Now we will sort these pairs on the basis of their intersection with left boundary. After that, we will loop over these pairs one by one and if for any two consecutive pairs, the second value of the current pair is less than that of the second value of the previous pair then there must be an intersection in the given vertical section.
The possible orientation of two consecutive pairs can be seen in above diagram for L1 and L2. We can see that when the second value is less, intersection lies in vertical section.
Total time complexity of solution will be O(n logn)
CPP
Java
Python3
C#
Javascript
class line {
constructor() {}
constructor(m, b){
this .m = m;
this .b = b;
}
};
function getYFromLine(l, x){
return (l.m * x + l.b);
}
function isIntersectionPointInsideSection(lines, xL, xR, N){
let yBoundary = new Array(N);
for (let i = 0; i < N; i++){
yBoundary[i] = [getYFromLine(lines[i], xL), getYFromLine(lines[i], xR)];
}
yBoundary.sort();
for (let i = 1; i < N; i++) {
if (yBoundary[i][1] < yBoundary[i - 1][1]){
return true ;
}
}
return false ;
}
{
let N = 4;
let m = [ 1, -1, 0, 2 ];
let b = [2, 7, -3, -7 ];
let lines = new Array();
for (let i = 0; i < N; i++) {
lines.push( new line(m[i], b[i]));
}
let xL = 2;
let xR = 4;
if (isIntersectionPointInsideSection(lines, xL, xR, N)) {
console.log( "Intersection point lies between " , xL, " and " , xR);
} else {
console.log( "No Intersection point lies between " , xL, " and " , xR);
}
}
|
Output
Intersection point lies between 2 and 4
Time Complexity: O(n*log(n))
Auxiliary Space: O(n)
Last Updated :
06 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...