Line Intersection

Problem

Design a simple Java class to implement the concept of a line in the Cartesian plane. Provide a method to test if the line intersects with another line.

Solution

Two points are enough to define a line in the Cartesian plane so we can use 4 private variables for that. For the intersection we can calculate the slope of each line then return true if they are different otherwise return false if the two lines are parallel because parallel lines have the same slope. This requires us to implement a slope method to calculate the slope of a given line. In case the same line is tested for intersection with itself then the result will be false using slope comparison method. It depends on our implementation for example we can leave it as is and say a line does not intersect with itself. On the other hand if you need the result to be true in case of same line comparison then you need calculate the Y intercept value and check if it is the same, in that case you return true because they are indeed the same line otherwise return false. In our implementation we will keep it simple and return false. One special case must be handled when the slope is infinity in case of perpendicular lines.

Code

Here is the code in Java

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *