Find intersection point of lines inside a section in C++


Suppose we have set of lines in the form y = mx + c. There are sections made by this line and the vertical section. We have to find the intersection point present in the given section or not. Suppose the lines are like −

L1 = y = x + 2

L2 = y = -x + 7

L3 = y = -3

L4 = y = 2x - 7

And the vertical section is given from x = 2 to x = 4.

Here intersection points of L1 and L2 are present inside this section, so the answer will be true.

To solve this problem, we will sue the sorting technique. First, we will calculate intersection point of each line with both the boundaries of vertical section. After that store that as a pair. We just need to store the y-coordinate values of intersections as a pair because x-coordinates are equal to boundary itself.

Now we will sort these pairs based on their intersection with left boundary. After that, we will loop over these pairs one by one. 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.

Example

 Live Demo

#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
class line {
   public:
      int slope, intercept;
      line(){
      }
      line(int slope, int intercept) : slope(slope), intercept(intercept) {
   }
};
int getYCoordinate(line l, int x) {
   return (l.slope * x + l.intercept);
}
bool hasIntersectionPoint(line lines[], int left_range, int right_range, int N) {
   pair<int, int> y_border[N];
   for (int i = 0; i < N; i++)
      y_border[i] = make_pair(getYCoordinate(lines[i], left_range), getYCoordinate(lines[i], right_range));
   sort(y_border, y_border + N);
   for (int i = 1; i < N; i++) {
      if (y_border[i].second < y_border[i - 1].second)
         return true;
   }
   return false;
}
int main() {
   int N = 4;
   int slope[] = { 1, -1, 0, 2 };
   int intercept[] = { 2, 7, -3, -7 };
   line lines[N];
   for (int i = 0; i < N; i++)
      lines[i] = line(slope[i], intercept[i]);
   int left_range = 2;
   int right_range = 4;
   if (hasIntersectionPoint(lines, left_range, right_range, N)) {
      cout << "The intersection point is lies between " << left_range << " and " << right_range;
   } else {
      cout << "No intersection point is present in between " << left_range << " and " << right_range;
   }
}

Output

The intersection point is lies between 2 and 4

Updated on: 03-Jan-2020

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements