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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
//Put this class in a separate file //and name it Line.java public class Line { //First point private float m_x1; private float m_y1; //Second point private float m_x2; private float m_y2; //Constructor takes two points public Line(float x1, float y1, float x2, float y2) { this.m_x1 = x1; this.m_y1 = y1; this.m_x2 = x2; this.m_y2 = y2; } //Calculates slope of the line public float Slope() { //Calculate numerator and denominator //of the slope float num = this.m_y2 - this.m_y1; float den = this.m_x2 - this.m_x1; //In case of a perpendicular line slope //is infinity so we return some number //to prevent division by zero if (den == 0) { return -999; } else { //Slope is (y2-y1)/(x2-x1) return num/den; } } //Tests for intersection with another line public boolean IntersectsWith(Line line) { return this.Slope() != line.Slope(); } } //Put this class in a separate file //and name it TestLine.java public class TestLine { //Main function public static void main(String[] args) { //Define two lines Line line1 = new Line(-10, 0, 10, 0); Line line2 = new Line(-10, 10, 10, 10); //Test for intersection if (line1.IntersectsWith(line2)) { System.out.println("They intersect"); } else { System.out.println("They do not intersect"); } } } |