The Wayback Machine - https://web.archive.org/web/20240927180551/https://www.geeksforgeeks.org/program-for-point-of-intersection-of-two-lines/
Open In App

Program for Point of Intersection of Two Lines

Last Updated : 16 Jun, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given points A and B corresponding to line AB and points P and Q corresponding to line PQ, find the point of intersection of these lines. The points are given in 2D Plane with their X and Y Coordinates. Examples:

Input : A = (1, 1), B = (4, 4)
        C = (1, 8), D = (2, 4)
Output : The intersection of the given lines 
         AB and CD is: (2.4, 2.4)

Input : A = (0, 1), B = (0, 4)
        C = (1, 8), D = (1, 4)
Output : The given lines AB and CD are parallel.

First of all, let us assume that we have two points (x1, y1) and (x2, y2). Now, we find the equation of line formed by these points. Let the given lines be :

  1. a1x + b1y = c1
  2. a2x + b2y = c2

We have to now solve these 2 equations to find the point of intersection. To solve, we multiply 1. by b2 and 2 by b1 This gives us, a1b2x + b1b2y = c1b2 a2b1x + b2b1y = c2b1 Subtracting these we get, (a1b2 – a2b1) x = c1b2 – c2b1 This gives us the value of x. Similarly, we can find the value of y. (x, y) gives us the point of intersection. Note: This gives the point of intersection of two lines, but if we are given line segments instead of lines, we have to also recheck that the point so computed actually lies on both the line segments. If the line segment is specified by points (x1, y1) and (x2, y2), then to check if (x, y) is on the segment we have to just check that

  • min (x1, x2) <= x <= max (x1, x2)
  • min (y1, y2) <= y <= max (y1, y2)

The pseudo code for the above implementation:

determinant = a1 b2 - a2 b1
if (determinant == 0)
{
    // Lines are parallel
}
else
{
    x = (c1b2 - c2b1)/determinant
    y = (a1c2 - a2c1)/determinant
}

These can be derived by first getting the slope directly and then finding the intercept of the line. 

C++




// C++ Implementation. To find the point of
// intersection of two lines
#include <bits/stdc++.h>
using namespace std;
 
// This pair is used to store the X and Y
// coordinates of a point respectively
#define pdd pair<double, double>
 
// Function used to display X and Y coordinates
// of a point
void displayPoint(pdd P)
{
    cout << "(" << P.first << ", " << P.second
         << ")" << endl;
}
 
pdd lineLineIntersection(pdd A, pdd B, pdd C, pdd D)
{
    // Line AB represented as a1x + b1y = c1
    double a1 = B.second - A.second;
    double b1 = A.first - B.first;
    double c1 = a1*(A.first) + b1*(A.second);
 
    // Line CD represented as a2x + b2y = c2
    double a2 = D.second - C.second;
    double b2 = C.first - D.first;
    double c2 = a2*(C.first)+ b2*(C.second);
 
    double determinant = a1*b2 - a2*b1;
 
    if (determinant == 0)
    {
        // The lines are parallel. This is simplified
        // by returning a pair of FLT_MAX
        return make_pair(FLT_MAX, FLT_MAX);
    }
    else
    {
        double x = (b2*c1 - b1*c2)/determinant;
        double y = (a1*c2 - a2*c1)/determinant;
        return make_pair(x, y);
    }
}
 
// Driver code
int main()
{
    pdd A = make_pair(1, 1);
    pdd B = make_pair(4, 4);
    pdd C = make_pair(1, 8);
    pdd D = make_pair(2, 4);
 
    pdd intersection = lineLineIntersection(A, B, C, D);
 
    if (intersection.first == FLT_MAX &&
        intersection.second==FLT_MAX)
    {
        cout << "The given lines AB and CD are parallel.\n";
    }
 
    else
    {
        // NOTE: Further check can be applied in case
        // of line segments. Here, we have considered AB
        // and CD as lines
        cout << "The intersection of the given lines AB "
                "and CD is: ";
        displayPoint(intersection);
    }
 
    return 0;
}


Java




// Java Implementation. To find the point of
// intersection of two lines
 
// Class used to  used to store the X and Y
// coordinates of a point respectively
class Point
{
    double x,y;
     
    public Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
     
    // Method used to display X and Y coordinates
    // of a point
    static void displayPoint(Point p)
    {
        System.out.println("(" + p.x + ", " + p.y + ")");
    }
}
 
class Test
{    
    static Point lineLineIntersection(Point A, Point B, Point C, Point D)
    {
        // Line AB represented as a1x + b1y = c1
        double a1 = B.y - A.y;
        double b1 = A.x - B.x;
        double c1 = a1*(A.x) + b1*(A.y);
      
        // Line CD represented as a2x + b2y = c2
        double a2 = D.y - C.y;
        double b2 = C.x - D.x;
        double c2 = a2*(C.x)+ b2*(C.y);
      
        double determinant = a1*b2 - a2*b1;
      
        if (determinant == 0)
        {
            // The lines are parallel. This is simplified
            // by returning a pair of FLT_MAX
            return new Point(Double.MAX_VALUE, Double.MAX_VALUE);
        }
        else
        {
            double x = (b2*c1 - b1*c2)/determinant;
            double y = (a1*c2 - a2*c1)/determinant;
            return new Point(x, y);
        }
    }
     
    // Driver method
    public static void main(String args[])
    {
        Point A = new Point(1, 1);
        Point B = new Point(4, 4);
        Point C = new Point(1, 8);
        Point D = new Point(2, 4);
      
        Point intersection = lineLineIntersection(A, B, C, D);
      
        if (intersection.x == Double.MAX_VALUE &&
            intersection.y == Double.MAX_VALUE)
        {
            System.out.println("The given lines AB and CD are parallel.");
        }
      
        else
        {
            // NOTE: Further check can be applied in case
            // of line segments. Here, we have considered AB
            // and CD as lines
           System.out.print("The intersection of the given lines AB " +
                               "and CD is: ");
           Point.displayPoint(intersection);
        }
    }
}


Python3




# Python program to find the point of
# intersection of two lines
 
# Class used to  used to store the X and Y
# coordinates of a point respectively
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
    # Method used to display X and Y coordinates
    # of a point
    def displayPoint(self, p):
        print(f"({p.x}, {p.y})")
 
 
def lineLineIntersection(A, B, C, D):
    # Line AB represented as a1x + b1y = c1
    a1 = B.y - A.y
    b1 = A.x - B.x
    c1 = a1*(A.x) + b1*(A.y)
 
    # Line CD represented as a2x + b2y = c2
    a2 = D.y - C.y
    b2 = C.x - D.x
    c2 = a2*(C.x) + b2*(C.y)
 
    determinant = a1*b2 - a2*b1
 
    if (determinant == 0):
        # The lines are parallel. This is simplified
        # by returning a pair of FLT_MAX
        return Point(10**9, 10**9)
    else:
        x = (b2*c1 - b1*c2)/determinant
        y = (a1*c2 - a2*c1)/determinant
        return Point(x, y)
 
 
# Driver code
A = Point(1, 1)
B = Point(4, 4)
C = Point(1, 8)
D = Point(2, 4)
 
intersection = lineLineIntersection(A, B, C, D)
 
if (intersection.x == 10**9 and intersection.y == 10**9):
    print("The given lines AB and CD are parallel.")
else:
    # NOTE: Further check can be applied in case
    # of line segments. Here, we have considered AB
    # and CD as lines
    print("The intersection of the given lines AB " + "and CD is: ")
    intersection.displayPoint(intersection)
 
 
# This code is contributed by Saurabh Jaiswal


C#




using System;
 
// C# Implementation. To find the point of
// intersection of two lines
 
// Class used to  used to store the X and Y
// coordinates of a point respectively
public class Point
{
    public double x, y;
 
    public Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
 
    // Method used to display X and Y coordinates
    // of a point
    public static void displayPoint(Point p)
    {
        Console.WriteLine("(" + p.x + ", " + p.y + ")");
    }
}
 
public class Test
{
    public static Point lineLineIntersection(Point A, Point B, Point C, Point D)
    {
        // Line AB represented as a1x + b1y = c1
        double a1 = B.y - A.y;
        double b1 = A.x - B.x;
        double c1 = a1 * (A.x) + b1 * (A.y);
 
        // Line CD represented as a2x + b2y = c2
        double a2 = D.y - C.y;
        double b2 = C.x - D.x;
        double c2 = a2 * (C.x) + b2 * (C.y);
 
        double determinant = a1 * b2 - a2 * b1;
 
        if (determinant == 0)
        {
            // The lines are parallel. This is simplified
            // by returning a pair of FLT_MAX
            return new Point(double.MaxValue, double.MaxValue);
        }
        else
        {
            double x = (b2 * c1 - b1 * c2) / determinant;
            double y = (a1 * c2 - a2 * c1) / determinant;
            return new Point(x, y);
        }
    }
 
    // Driver method
    public static void Main(string[] args)
    {
        Point A = new Point(1, 1);
        Point B = new Point(4, 4);
        Point C = new Point(1, 8);
        Point D = new Point(2, 4);
 
        Point intersection = lineLineIntersection(A, B, C, D);
 
        if (intersection.x == double.MaxValue && intersection.y == double.MaxValue)
        {
            Console.WriteLine("The given lines AB and CD are parallel.");
        }
 
        else
        {
            // NOTE: Further check can be applied in case
            // of line segments. Here, we have considered AB
            // and CD as lines
           Console.Write("The intersection of the given lines AB " + "and CD is: ");
           Point.displayPoint(intersection);
        }
    }
}
 
  // This code is contributed by Shrikant13


Javascript




<script>
    // Javascript program to find the point of
    // intersection of two lines
       
    // Class used to  used to store the X and Y
    // coordinates of a point respectively    
    class Point
    {
        constructor(x, y)
        {
            this.x = x;
            this.y = y;
        }
         
        // Method used to display X and Y coordinates
        // of a point
        displayPoint(p){
            document.write("(" + p.x + ", " + p.y + ")");
        }
    }
     
    function lineLineIntersection(A,B,C,D){
        // Line AB represented as a1x + b1y = c1
        var a1 = B.y - A.y;
        var b1 = A.x - B.x;
        var c1 = a1*(A.x) + b1*(A.y);
        
        // Line CD represented as a2x + b2y = c2
        var a2 = D.y - C.y;
        var b2 = C.x - D.x;
        var c2 = a2*(C.x)+ b2*(C.y);
        
        var determinant = a1*b2 - a2*b1;
        
        if (determinant == 0)
        {
            // The lines are parallel. This is simplified
            // by returning a pair of FLT_MAX
            return new Point(Number.MAX_VALUE, Number.MAX_VALUE);
        }
        else
        {
            var x = (b2*c1 - b1*c2)/determinant;
            var y = (a1*c2 - a2*c1)/determinant;
            return new Point(x, y);
        }
    }
      
    // Driver code
    let A = new Point(1, 1);
    let B = new Point(4, 4);
    let C = new Point(1, 8);
    let D = new Point(2, 4);
     
    var intersection = lineLineIntersection(A, B, C, D);
     
    if (intersection.x == Number.MAX_VALUE && intersection.y == Number.MAX_VALUE){
        document.write("The given lines AB and CD are parallel.");
    }else{
        // NOTE: Further check can be applied in case
        // of line segments. Here, we have considered AB
        // and CD as lines
       document.write("The intersection of the given lines AB " + "and CD is: ");
       intersection.displayPoint(intersection);
    }
     
    // This code is contributed by shruti456rawal
</script>


Output:

The intersection of the given lines AB and 
CD is: (2.4, 2.4)

Time Complexity: O(1) 
Auxiliary Space: O(1)



Similar Reads

Find intersection point of lines inside a section
Given N lines in two-dimensional space in y = mx + b form and a vertical section. We need to find out whether there is an intersection point inside the given section or not. Examples: In below diagram four lines are there, L1 : y = x + 2 L2 : y = -x + 7 L3 : y = -3 L4 : y = 2x – 7 and vertical section is given from x = 2 to x = 4 We can see that in
9 min read
Javascript Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge.  Above diagram shows an example with two linked lists having 15 as intersection points. Method 1(Simply use
7 min read
Ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles
Given two circles of given radii, such that the circles don’t touch each other, the task is to find the ratio of the distance between the centers of the circles and the point of intersection of two direct common tangents to the circles. Examples: Input: r1 = 4, r2 = 6 Output: 2:3 Input: r1 = 22, r2 = 43 Output: 22:43 Approach: Let the radii of the
5 min read
Ratio of the distance between the centers of the circles and the point of intersection of two transverse common tangents to the circles
Given two circles, of given radii, such that the circles don’t touch each other. The task is to find the ratio of the distance between the centres of the circles and the point of intersection of two transverse common tangents to the circles.Examples: Input :r1 = 4, r2 = 8 Output :1:2 Input :r1 = 5, r2 = 13 Output :5:13 Approach: Let the radii of th
5 min read
Find intersection point of two Linked Lists without finding the length
There are two singly linked lists in a system. By some programming error, the end node of one of the linked lists got linked to the second list, forming an inverted Y shaped list. Write a program to get the point where both the linked lists merge. Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> 6 ^ | 7 -> 8 -> 9 Output: 4 Input: 13 -
7 min read
Intersection point of two Linked List by marking visited nodes
Given two linked lists of size N and M consisting of positive value nodes, having a common intersection point, the task is to find the intersection point of the two linked lists where they merge. Examples: Input: L1: 3 ? 6 ? 9 ? 15 ? 30, L2: 10 ? 15 ? 30Output: 15Explanation: From the above image, the intersection point of the two linked lists is 1
7 min read
Write a function to get the intersection point of two Linked Lists
Given two singly linked lists that merge into a single Y-shaped list. The two lists initially have distinct paths but eventually converge at a common node, forming a Y-shape, the task is to find and return the node where the two lists merge. The above diagram shows an example with two linked lists having 15 as intersection point. Table of Content [
15+ min read
Maximum points of intersection n lines
You are given n straight lines. You have to find a maximum number of points of intersection with these n lines.Examples: Input : n = 4 Output : 6 Input : n = 2Output :1 Approach : As we have n number of line, and we have to find the maximum point of intersection using this n line. So this can be done using the combination. This problem can be thoug
3 min read
Number of pairs of lines having integer intersection points
Given two integer arrays P[] and Q[], where pi and qj for each 0 <= i < size(P) and 0 <= j < size(Q) represents the line equations x - y = -pi and x + y = qj respectively. The task is to find the number of pairs from P[] and Q[] having integer intersection points. Examples: Input: P[] = {1, 3, 2}, Q[] = {3, 0} Output: 3 The pairs of lin
5 min read
Check if N given lines can be intersected by K vertical lines
Given N horizontal lines represented by an array position[][] of size N, where position[i] represents the ith horizontal line which has x-coordinates from position[i][0] to position[i][1] and an integer K, which represents the maximum number of vertical lines that can be drawn, the task is to check if N given lines can be intersected by at most K v
6 min read
Number of parallelograms when n horizontal parallel lines intersect m vertical parallel lines
Given two positive integers n and m. The task is to count number of parallelogram that can be formed of any size when n horizontal parallel lines intersect with m vertical parallel lines. Examples: Input : n = 3, m = 2Output : 32 parallelograms of size 1x1 and 1 parallelogram of size 2x1.Input : n = 5, m = 5Output : 100 The idea is to use Combinati
8 min read
Maximum distinct lines passing through a single point
Given [Tex]N [/Tex]lines represented by two points [Tex](x1, y1) [/Tex]and [Tex](x2, y2) [/Tex]. The task is to find maximum number of lines which can pass through a single point, without superimposing (or covering) any other line. We can move any line but not rotate it.Examples: Input : Line 1 : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Line 2 : x2 = 2, y1 =
6 min read
Count straight lines intersecting at a given point
Given a matrix lines[][] of size N * 3, such that ith row denotes a line having the equation lines[i][0] * x + lines[i][1]*y = lines[i][2], and integers X and Y, denoting coordinates of a point (X, Y), the task is to count the number of lines from the given matrix which intersect with one another at the given point (X, Y). Examples: Input: N=5, X =
8 min read
Javascript Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6Second linked list be 2->4->6->8, Output: 2->4->6.The elements
3 min read
Reflection of a point at 180 degree rotation of another point
Given two points coordinates (x1, y1) and (x2, y2)on 2D plane. The task is to find the reflection of (x1, y1) at 180 degree rotation of (x2, y2).Examples: Input : x1 = 0, y1 = 0, x2 = 1, y2 = 1 Output : (2, 2) Input : x1 = 1, y1 = 1, x2 = 2, y2 = 2 Output : (3, 3) Let the reflection point of point (x1, y1) about (x2, y2) be (x', y'). For (x', y') b
4 min read
Find time required to reach point N from point 0 according to given rules
Given two positive integers X and Y and N number of points arranged in a line, the task is to find the time required to reach point N from point 0 according to the following rules: Every point has one barrier that closes after every Y minutes and remains closed for the next Y minutes.On reaching a point if the barrier is closed, then the person nee
7 min read
Rotation of a point about another point
We have already discussed the rotation of a point P about the origin in the Set 1 and Set 2. The rotation of point P about origin with an angle ? in the anti-clockwise direction is given as under: Rotation of P about origin: P * polar(1.0, ?)Rotation of P about point Q Now, we have to rotate the point P not about origin but about a general point Q.
8 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Find the intersection of two Matrices
Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where: Cij = Aij if Aij = BijC = "*", otherwise. Examples: Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4, 5, 3, 4}}; Output : * 4 * 8 1 3 5 7 8 * * 2 * 5
6 min read
Find intersection of intervals given by two lists
Given two 2-D arrays which represent intervals. Each 2-D array represents a list of intervals. Each list of intervals is disjoint and sorted in increasing order. Find the intersection or set of ranges that are common to both the lists. Disjoint means no element is common in a list. Example: {1, 4} and {5, 6} are disjoint while {1, 4} and {2, 5} are
7 min read
Union and Intersection of two Graphs
Given two graphs G1 and G2, the task is to find the union and intersection of the two given graphs, i.e. (G1 ∪ G2) and (G1 ∩ G2). Examples: Input: G1 = { ("e1", 1, 2), ("e2", 1, 3), ("e3", 3, 4), ("e4", 2, 4) }, G2 = = { ("e4", 2, 4), ("e5", 2, 5), ("e6", 4, 5) }Output:G1 union G2 ise1 1 2e2 1 3e3 3 4e4 2 4e5 2 5e6 4 5G1 intersection G2 ise4 2 4Exp
12 min read
Angle of intersection of two circles having their centers D distance apart
Given two positive integers R1 and R2 representing the radius of two intersecting circles having a distance D between their centers, the task is to find the cosine of the angle of intersection between the two circles. Examples: Input: R1 = 3, R2 = 4, D = 5Output: 0 Input: R1 = 7, R2 = 3, D = 6Output: 0.52381 Approach: The given problem can be solve
4 min read
Area of intersection of two Circles
Given the coordinates of the centers of two circles (X1, Y1) and (X2, Y2) as well as the radii of the respective circles R1 and R2. Find the floor of the area of their intersection. Note: Use the value of Pi as 3.14 Examples: Input: X1 = 0, Y1 = 0, R1 = 4, X2 = 6, Y2 = 0, R2 = 4Output: 7Explanation: The intersecting area equals 7.25298806. So, Answ
8 min read
POTD Solutions | 19 Nov' 23 | Intersection of two sorted linked lists
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Linked List but will also help you build up problem-solving skills. POTD 19 November: Intersection of two
4 min read
Union and Intersection of two sorted arrays
Given two sorted arrays, find their union and intersection. Example: Input: arr1[] = {1, 3, 4, 5, 7} arr2[] = {2, 3, 5, 6} Output: Union : {1, 2, 3, 4, 5, 6, 7} Intersection : {3, 5} Input: arr1[] = {2, 5, 6} arr2[] = {4, 6, 8, 10} Output: Union : {2, 4, 5, 6, 8, 10} Intersection : {6} Union of Two-Sorted Arrays using SetsThe idea of the approach i
15+ min read
Intersection of two Sorted Linked Lists
Given the head of two sorted linked lists, the task is to create a new linked list that represents the intersection of the two original lists. The new linked list should be created without modifying the original lists. Note: The elements in the linked lists are not necessarily distinct. Example: Input: head1 = 1->2->3->4->6, head2 = 2-
15+ min read
Find Union and Intersection of two unsorted arrays
Given two unsorted arrays that represent two sets (elements in every array are distinct), find the union and intersection of two arrays. Example: Input : arr1[] = {7, 1, 5, 2, 3, 6}, arr2[] = {3, 8, 6, 20, 7} Output : Union : {1, 2, 3, 5, 6, 7, 8, 20} Intersection : {3, 6, 7}Note that the elements of union and intersection can be printed in any ord
15+ min read
Union and Intersection of two Linked List using Merge Sort
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two lists contains distinct node values. Note: The order of elements in output lists doesn't matter. Examples: Input: head1: 10 -> 15 -> 4 -> 20head2: 8 -> 4 -> 2 -> 10O
15+ min read
Union and Intersection of two Linked Lists
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesn’t matter. Example: Input: head1: 10 -> 15 -> 4 -> 20head2: 8 -> 4 -> 2 -
15+ min read
Union and Intersection of two Linked List using Hashing
Given two singly Linked Lists, create union and intersection lists that contain the union and intersection of the elements present in the given lists. Each of the two linked lists contains distinct node values.Note: The order of elements in output lists doesn’t matter. Examples: Input:head1 : 10 -> 15 -> 4 -> 20head2 : 8 -> 4 -> 2 -
10 min read
Article Tags :
Practice Tags :