There is lot of math involve in finding if two line are intersecting. check the link for math behind it. The python implementation of the same is below
import numpy as np
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
class Line:
def __init__(self, x: Point, y: Point):
self.p1 = x
self.p2 = y
def find_intersection(l1, l2):
def slope(l):
return (l.p2.y - l.p1.y)/(l.p2.x - l.p1.x)
def intercept(l, m):
return l.p1.y - m*l.p1.x
m1 = slope(l1)
m2 = slope(l2)
b1 = intercept(l1, m1)
b2 = intercept(l2, m2)
A = np.array([
[-m1, 1],
[-m2, 1]
])
b = np.array([[b1],[b2]])
return np.dot(np.linalg.inv(A), b)
# check whether p is on the line or not
def onLine(l1: Line, p: Point):
return True if p.x <= max(l1.p1.x, l1.p2.x) and p.x <= min(l1.p1.x, l1.p2.x) and p.y <= max(l1.p1.y, l1.p2.y) and p.y <= min(l1.p1.y, l1.p2.y) else False
def direction(a, b, c):
val = (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y);
if val == 0:
return 0 # colinear
elif val < 0:
return 2 # anti-clockwise direction
return 1 # clockwise direction
def isIntersect(l1: Line, l2: Line):
#four direction for two lines and points of other line
dir1 = direction(l1.p1, l1.p2, l2.p1);
dir2 = direction(l1.p1, l1.p2, l2.p2);
dir3 = direction(l2.p1, l2.p2, l1.p1);
dir4 = direction(l2.p1, l2.p2, l1.p2);
if dir1 != dir2 and dir3 != dir4 :
return True, find_intersection(l1, l2)
if dir1==0 and onLine(l1, l2.p1): # when p2 of line2 are on the line1
return True, l1.p1
if dir2==0 and onLine(l1, l2.p2): # when p1 of line2 are on the line1
return True, l2.p2
if dir3==0 and onLine(l2, l1.p1): #when p2 of line1 are on the line2
return True, l1.p1
if dir4==0 and onLine(l2, l1.p2): #when p1 of line1 are on the line2
return True, l1.p2
return False, None
Test Cases:
isIntersect(Line(Point(15, 10), Point(49,25)),
Line(Point(32, 32), Point(29,5)))
isIntersect(Line(Point(0, 0), Point(5, 5)),
Line(Point(5, 6), Point(3, 10)))
- If the points are co-linear then return one of them (infinite solutions)
- If the points are not co-linear and intersect then there is one unique solution. Convert the two lines into standard line equations find the intersection by solving the equations using matrix inverse. ie. find
inverse(A).b