Program for Point of Intersection of Two Lines
Last Updated :
16 Jun, 2022
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 :
- a1x + b1y = c1
- 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
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem