Skip to content
DeepForgeby svx
All problems
MediumLinear Algebrala-070

Line Intersection 2D

Problem

Find the intersection of two lines in 2D. Line 1 passes through p with direction r and line 2 passes through q with direction s.

With cross(u, v) = u[0]*v[1] - u[1]*v[0], compute t = cross(q - p, s) / cross(r, s); the point is p + t*r. Return None if cross(r, s) == 0 (parallel or collinear lines).

Hint

Use the 2D cross product to find the parameter t along the first line.

Test cases

case 1
in: [[0,0],[1,1],[0,1],[1,-1]]
expected: [0.5,0.5]
case 2
in: [[0,0],[2,0],[1,-1],[0,1]]
expected: [1,0]
case 3
in: [[0,0],[1,0],[0,1],[1,0]]
expected: null
case 4
in: [[0,0],[1,0],[0,0],[0,1]]
expected: [0,0]
Starter codePython
def line_intersection(p, r, q, s):
    # Your code here
    pass

4 test cases · run your code against them in the editor