The Wayback Machine - https://web.archive.org/web/20241119101653/https://www.geeksforgeeks.org/basic-geometry-for-competitive-programming/
Open In App

Basic Geometry for Competitive Programming

Last Updated : 11 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Ever wondered how to tackle tricky problems in competitive programming? Well, basic geometry is your secret weapon! In this article, we’re diving into the basics Geometric Algorithms. It’s like a power-up for your problem-solving skills, giving you the tools to crack those coding challenges like a pro.

What are Geometric Algorithms?

Geometric algorithms are a set of computational techniques used in Competitive Programming to solve problems related to geometry and spatial relationships. These problems often involve points, lines, polygons, and other geometric objects.

Why to use Geometric Algorithms?

There are several questions which require basic geometric algorithms like:

  1. Vector Addition/Subtraction
  2. Dot Product and Cross Product
  3. Distance of a point from a line
  4. Intersection of Lines
  5. Intersection of Planes, etc.

1. Vector Addition/Subtraction:

Operations like addition and subtraction of two vectors can be simply done by performing the operation on the individual components of the vectors. Like if we have two vectors (x1, y1) and (x2, y2), then the sum of the two vectors is (x1+x2, y1+y2) and the difference between them is (x1-x2, y1-y2).

Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to perform vector addition
vector<int> addVectors(const vector<int>& v1,
                    const vector<int>& v2)
{
    vector<int> result;
    if (v1.size() != v2.size()) {
        cerr << "Vectors must be of the same size for "
                "addition."
            << endl;
        return result; // Returning an empty vector
                    // indicating an error
    }

    result.reserve(v1.size());
    for (size_t i = 0; i < v1.size(); ++i) {
        result.push_back(v1[i] + v2[i]);
    }

    return result;
}

// Function to perform vector subtraction
vector<int> subtractVectors(const vector<int>& v1,
                            const vector<int>& v2)
{
    vector<int> result;
    if (v1.size() != v2.size()) {
        cerr << "Vectors must be of the same size for "
                "subtraction."
            << endl;
        return result; // Returning an empty vector
                    // indicating an error
    }

    result.reserve(v1.size());
    for (size_t i = 0; i < v1.size(); ++i) {
        result.push_back(v1[i] - v2[i]);
    }

    return result;
}

// Driver code
int main()
{

    // Example vectors
    vector<int> vector1 = { 1, 2, 3, 4, 5 };
    vector<int> vector2 = { 5, 4, 3, 2, 1 };

    // Perform vector addition
    vector<int> sum = addVectors(vector1, vector2);
    cout << "Vector Addition Result: ";
    for (int value : sum) {
        cout << value << " ";
    }
    cout << endl;

    // Perform vector subtraction
    vector<int> difference
        = subtractVectors(vector1, vector2);
    cout << "Vector Subtraction Result: ";
    for (int value : difference) {
        cout << value << " ";
    }
    cout << endl;

    return 0;
}
Java
import java.util.Arrays;

public class VectorOperations {

    // Function for vector addition
    public static int[] addVectors(int[] v1, int[] v2) {
        int[] result = new int[v1.length];

        // Check if vectors are of the same size for addition
        if (v1.length != v2.length) {
            System.out.println("Vectors must be of the same size for addition.");
            // Returning an empty array indicating an error
            return result;
        }

        // Perform vector addition
        for (int i = 0; i < v1.length; i++) {
            result[i] = v1[i] + v2[i];
        }

        return result;
    }

    // Function for vector subtraction
    public static int[] subtractVectors(int[] v1, int[] v2) {
        int[] result = new int[v1.length];

        // Check if vectors are of the same size for subtraction
        if (v1.length != v2.length) {
            System.out.println("Vectors must be of the same size for subtraction.");
            // Returning an empty array indicating an error
            return result;
        }

        // Perform vector subtraction
        for (int i = 0; i < v1.length; i++) {
            result[i] = v1[i] - v2[i];
        }

        return result;
    }

    public static void main(String[] args) {
        // Example vectors
        int[] vector1 = {1, 2, 3, 4, 5};
        int[] vector2 = {5, 4, 3, 2, 1};

        // Perform vector addition
        int[] sumResult = addVectors(vector1, vector2);
        System.out.println("Vector Addition Result: " + Arrays.toString(sumResult));

        // Perform vector subtraction
        int[] differenceResult = subtractVectors(vector1, vector2);
        System.out.println("Vector Subtraction Result: " + Arrays.toString(differenceResult));
    }
}
Python3
def add_vectors(v1, v2):
    result = []
    if len(v1) != len(v2):
        print("Vectors must be of the same size for addition.")
        return result  # Returning an empty list indicating an error

    result = [x + y for x, y in zip(v1, v2)]
    return result

def subtract_vectors(v1, v2):
    result = []
    if len(v1) != len(v2):
        print("Vectors must be of the same size for subtraction.")
        return result  # Returning an empty list indicating an error

    result = [x - y for x, y in zip(v1, v2)]
    return result

# Example vectors
vector1 = [1, 2, 3, 4, 5]
vector2 = [5, 4, 3, 2, 1]

# Perform vector addition
sum_result = add_vectors(vector1, vector2)
print("Vector Addition Result:", *sum_result)

# Perform vector subtraction
difference_result = subtract_vectors(vector1, vector2)
print("Vector Subtraction Result:", *difference_result)
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to perform vector addition
    static List<int> AddVectors(List<int> v1, List<int> v2)
    {
        List<int> result = new List<int>();

        if (v1.Count != v2.Count)
        {
            Console.WriteLine("Vectors must be of the same size for addition.");
            return result; // Returning an empty list indicating an error
        }

        for (int i = 0; i < v1.Count; ++i)
        {
            result.Add(v1[i] + v2[i]);
        }

        return result;
    }

    // Function to perform vector subtraction
    static List<int> SubtractVectors(List<int> v1, List<int> v2)
    {
        List<int> result = new List<int>();

        if (v1.Count != v2.Count)
        {
            Console.WriteLine("Vectors must be of the same size for subtraction.");
            return result; // Returning an empty list indicating an error
        }

        for (int i = 0; i < v1.Count; ++i)
        {
            result.Add(v1[i] - v2[i]);
        }

        return result;
    }

    // Driver code
    static void Main()
    {
        // Example lists
        List<int> vector1 = new List<int> { 1, 2, 3, 4, 5 };
        List<int> vector2 = new List<int> { 5, 4, 3, 2, 1 };

        // Perform vector addition
        List<int> sum = AddVectors(vector1, vector2);
        Console.Write("Vector Addition Result: ");
        foreach (int value in sum)
        {
            Console.Write(value + " ");
        }
        Console.WriteLine();

        // Perform vector subtraction
        List<int> difference = SubtractVectors(vector1, vector2);
        Console.Write("Vector Subtraction Result: ");
        foreach (int value in difference)
        {
            Console.Write(value + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// Function for vector addition
function addVectors(v1, v2) {
    let result = new Array(v1.length).fill(0);

    // Check if vectors are of the same size for addition
    if (v1.length !== v2.length) {
        console.log("Vectors must be of the same size for addition.");
        // Returning an empty array indicating an error
        return result;
    }

    // Perform vector addition
    for (let i = 0; i < v1.length; i++) {
        result[i] = v1[i] + v2[i];
    }

    return result;
}

// Function for vector subtraction
function subtractVectors(v1, v2) {
    let result = new Array(v1.length).fill(0);

    // Check if vectors are of the same size for subtraction
    if (v1.length !== v2.length) {
        console.log("Vectors must be of the same size for subtraction.");
        // Returning an empty array indicating an error
        return result;
    }

    // Perform vector subtraction
    for (let i = 0; i < v1.length; i++) {
        result[i] = v1[i] - v2[i];
    }

    return result;
}

// Example vectors
let vector1 = [1, 2, 3, 4, 5];
let vector2 = [5, 4, 3, 2, 1];

// Perform vector addition
let sumResult = addVectors(vector1, vector2);
console.log("Vector Addition Result: " + sumResult);

// Perform vector subtraction
let differenceResult = subtractVectors(vector1, vector2);
console.log("Vector Subtraction Result: " + differenceResult);

Output
Vector Addition Result: 6 6 6 6 6 
Vector Subtraction Result: -4 -2 0 2 4 







2. Dot Product and Cross Product:

The dot product of two vectors is simply the sum of the products of the corresponding elements. If we have two vectors (x1, y1) and (x2, y2), then the dot product of the two vectors is (x1 * x2) + (y1 * y2). The dot product of two vectors is a scalar quantity.

If we have two vectors in x-y plane (x1, y1) and (x2, y2), then the magnitude of cross product of two vectors is (x1 * y2) – (x2 * y1) and direction is in Âąz direction. The cross product of two vectors is a vector quantity. Similarly, the cross product of two 3D vectors (x1, y1, z1) and (x2, y2, z2) is (y1*z2 – y2*z1, z1*x2 – z2*x1, x1*y2 – x2*y1).

Implementation:

C++
#include <iostream>
#include <vector>

using namespace std;

// Function to calculate the dot product of two vectors
double dotProduct(const vector<double>& vec1,
                const vector<double>& vec2)
{
    double result = 0;
    for (int i = 0; i < 3; ++i) {
        result += vec1[i] * vec2[i];
    }
    return result;
}

// Function to calculate the cross product of two vectors
vector<double> crossProduct(const vector<double>& vec1,
                            const vector<double>& vec2)
{
    vector<double> result(3, 0);
    result[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
    result[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
    result[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
    return result;
}

int main()
{
    // Example vectors
    vector<double> vector1 = { 1.0, 2.0, 3.0 };
    vector<double> vector2 = { 4.0, 5.0, 6.0 };

    // Calculate and display the dot product
    double dotResult = dotProduct(vector1, vector2);
    cout << "Dot Product: " << dotResult << endl;

    // Calculate and display the cross product
    vector<double> crossResult
        = crossProduct(vector1, vector2);
    cout << "Cross Product: ";
    for (double value : crossResult) {
        cout << value << " ";
    }
    cout << endl;

    return 0;
}
Java
import java.util.Arrays;
import java.util.List;

public class VectorOperations {

    // Function to calculate the dot product of two vectors
    public static double dotProduct(List<Double> vec1, List<Double> vec2) {
        double result = 0;
        for (int i = 0; i < 3; ++i) {
            result += vec1.get(i) * vec2.get(i);
        }
        return result;
    }

    // Function to calculate the cross product of two vectors
    public static List<Double> crossProduct(List<Double> vec1, List<Double> vec2) {
        List<Double> result = Arrays.asList(0.0, 0.0, 0.0);
        result.set(0, vec1.get(1) * vec2.get(2) - vec1.get(2) * vec2.get(1));
        result.set(1, vec1.get(2) * vec2.get(0) - vec1.get(0) * vec2.get(2));
        result.set(2, vec1.get(0) * vec2.get(1) - vec1.get(1) * vec2.get(0));
        return result;
    }

    public static void main(String[] args) {
        // Example vectors
        List<Double> vector1 = Arrays.asList(1.0, 2.0, 3.0);
        List<Double> vector2 = Arrays.asList(4.0, 5.0, 6.0);

        // Calculate and display the dot product
        double dotResult = dotProduct(vector1, vector2);
        System.out.println("Dot Product: " + dotResult);

        // Calculate and display the cross product
        List<Double> crossResult = crossProduct(vector1, vector2);
        System.out.print("Cross Product: ");
        for (double value : crossResult) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
}
Python3
class VectorOperations:
    @staticmethod
    def dot_product(vec1, vec2):
        result = 0
        for i in range(3):
            result += vec1[i] * vec2[i]
        return result

    @staticmethod
    def cross_product(vec1, vec2):
        result = [0.0, 0.0, 0.0]
        result[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1]
        result[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2]
        result[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0]
        return result

if __name__ == "__main__":
    # Example vectors
    vector1 = [1.0, 2.0, 3.0]
    vector2 = [4.0, 5.0, 6.0]

    # Calculate and display the dot product
    dot_result = VectorOperations.dot_product(vector1, vector2)
    print("Dot Product:", dot_result)

    # Calculate and display the cross product
    cross_result = VectorOperations.cross_product(vector1, vector2)
    print("Cross Product:", cross_result)
C#
using System;
using System.Collections.Generic;

class Program
{
    // Function to calculate the dot product of two vectors
    static double DotProduct(List<double> vec1, List<double> vec2)
    {
        double result = 0;
        for (int i = 0; i < 3; ++i)
        {
            result += vec1[i] * vec2[i];
        }
        return result;
    }

    // Function to calculate the cross product of two vectors
    static List<double> CrossProduct(List<double> vec1, List<double> vec2)
    {
        List<double> result = new List<double> { 0, 0, 0 };
        result[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
        result[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
        result[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
        return result;
    }

    static void Main()
    {
        // Example vectors
        List<double> vector1 = new List<double> { 1.0, 2.0, 3.0 };
        List<double> vector2 = new List<double> { 4.0, 5.0, 6.0 };

        // Calculate and display the dot product
        double dotResult = DotProduct(vector1, vector2);
        Console.WriteLine("Dot Product: " + dotResult);

        // Calculate and display the cross product
        List<double> crossResult = CrossProduct(vector1, vector2);
        Console.Write("Cross Product: ");
        foreach (double value in crossResult)
        {
            Console.Write(value + " ");
        }
        Console.WriteLine();
    }
}
JavaScript
// Function to calculate the dot product of two vectors
function dotProduct(vec1, vec2) {
    let result = 0;
    for (let i = 0; i < 3; ++i) {
        result += vec1[i] * vec2[i];
    }
    return result;
}

// Function to calculate the cross product of two vectors
function crossProduct(vec1, vec2) {
    let result = [0, 0, 0];
    result[0] = vec1[1] * vec2[2] - vec1[2] * vec2[1];
    result[1] = vec1[2] * vec2[0] - vec1[0] * vec2[2];
    result[2] = vec1[0] * vec2[1] - vec1[1] * vec2[0];
    return result;
}

// Example vectors
const vector1 = [1.0, 2.0, 3.0];
const vector2 = [4.0, 5.0, 6.0];

// Calculate and display the dot product
const dotResult = dotProduct(vector1, vector2);
console.log("Dot Product: " + dotResult);

// Calculate and display the cross product
const crossResult = crossProduct(vector1, vector2);
console.log("Cross Product: " + crossResult.join(" "));

Output
Dot Product: 32
Cross Product: -3 6 -3 





3. Distance from a point to a line:

Suppose we are given point A and a line L and we need to calculate the distance between the point and the line (say h), we can simply do it using Cross Product of vectors.

linePointDistance

Let’s say we take 2 points on the line L, say B and C so the distance between the point and the line would simply be:

[Tex]h = ( \,|\overrightarrow{\rm BA}| X |\overrightarrow{\rm BC}|) \,/(|\overrightarrow{\rm BC}|) [/Tex]

where the numerator is the magnitude of Cross Product of vector B to A and B to C and the denominator is the magnitude of vector B to C.

From the above diagram, we can see that the area of the parallelogram ABCD =

[Tex] (|\overrightarrow{\rm BA}| X |\overrightarrow{\rm BC}|) [/Tex]

Also, we know that area of a parallelogram = base * height = [Tex](|\overrightarrow{\rm BC}|) * h [/Tex]

So, using the above two equations, we can calculate the height h,

[Tex]h = ( \,|\overrightarrow{\rm BA}| X |\overrightarrow{\rm BC}|) \,/(|\overrightarrow{\rm BC}|) [/Tex]

Note: We can use the same formula for 3D vectors also.

Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Method to get the magnitude of a vector
double getMagnitude(vector<int>& v)
{
    return sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
}

// Method to calculate the cross product of two vectors v1
// and v2
void getCrossProduct(vector<int>& v1, vector<int>& v2,
                    vector<int>& crossProduct)
{
    crossProduct[0] = v1[1] * v2[2] - v1[2] * v2[1];
    crossProduct[1] = v1[2] * v2[0] - v1[0] * v2[2];
    crossProduct[2] = v1[0] * v2[1] - v1[1] * v2[0];
}

int main()
{
    // Point from which we need to calculate the distance
    vector<int> pointA = { 1, 4, -2 };

    // Points on the line P
    vector<int> pointB = { 3, 1, -2 };
    vector<int> pointC = { 6, -2, 1 };

    // vector BA
    vector<int> vecBA
        = { pointA[0] - pointB[0], pointA[1] - pointB[1],
            pointA[2] - pointB[2] };
    // vector BC
    vector<int> vecBC
        = { pointC[0] - pointB[0], pointC[1] - pointB[1],
            pointC[2] - pointB[2] };

    // vector to store the cross prduct
    vector<int> crossProduct(3);
    getCrossProduct(vecBA, vecBC, crossProduct);

    // Variable to store the distance of point A from line P
    double dist
        = getMagnitude(crossProduct) / getMagnitude(vecBC);

    cout << dist;

    return 0;
}
Java
import java.util.*;

// Class to hold the methods
public class Main {

    // Method to get the magnitude of a vector
    public static double getMagnitude(int[] v) {
        return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
    }

    // Method to calculate the cross product of two vectors v1 and v2
    public static int[] getCrossProduct(int[] v1, int[] v2) {
        int[] crossProduct = new int[3];
        crossProduct[0] = v1[1] * v2[2] - v1[2] * v2[1];
        crossProduct[1] = v1[2] * v2[0] - v1[0] * v2[2];
        crossProduct[2] = v1[0] * v2[1] - v1[1] * v2[0];
        return crossProduct;
    }

    public static void main(String[] args) {
        // Point from which we need to calculate the distance
        int[] pointA = { 1, 4, -2 };

        // Points on the line P
        int[] pointB = { 3, 1, -2 };
        int[] pointC = { 6, -2, 1 };

        // vector BA
        int[] vecBA = { pointA[0] - pointB[0], pointA[1] - pointB[1], pointA[2] - pointB[2] };
        // vector BC
        int[] vecBC = { pointC[0] - pointB[0], pointC[1] - pointB[1], pointC[2] - pointB[2] };

        // vector to store the cross product
        int[] crossProduct = getCrossProduct(vecBA, vecBC);

        // Variable to store the distance of point A from line P
        double dist = getMagnitude(crossProduct) / getMagnitude(vecBC);

        System.out.println(dist);
    }
}
Python
import math

# Method to get the magnitude of a vector
def get_magnitude(v):
    return math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])

# Method to calculate the cross product of two vectors v1
# and v2
def get_cross_product(v1, v2):
    cross_product = [0, 0, 0]
    cross_product[0] = v1[1] * v2[2] - v1[2] * v2[1]
    cross_product[1] = v1[2] * v2[0] - v1[0] * v2[2]
    cross_product[2] = v1[0] * v2[1] - v1[1] * v2[0]
    return cross_product

# Point from which we need to calculate the distance
pointA = [1, 4, -2]

# Points on the line P
pointB = [3, 1, -2]
pointC = [6, -2, 1]

# vector BA
vecBA = [pointA[0] - pointB[0], pointA[1] - pointB[1], pointA[2] - pointB[2]]
# vector BC
vecBC = [pointC[0] - pointB[0], pointC[1] - pointB[1], pointC[2] - pointB[2]]

# vector to store the cross product
cross_product = get_cross_product(vecBA, vecBC)

# Variable to store the distance of point A from line P
dist = get_magnitude(cross_product) / get_magnitude(vecBC)

print(dist)
C#
using System;

public class MainClass {
    // Method to calculate the magnitude of a vector
    static double GetMagnitude(int[] v)
    {
        return Math.Sqrt(v[0] * v[0] + v[1] * v[1]
                         + v[2] * v[2]);
    }

    // Method to calculate the cross product of two vectors
    // v1 and v2
    static void GetCrossProduct(int[] v1, int[] v2,
                                int[] crossProduct)
    {
        crossProduct[0] = v1[1] * v2[2] - v1[2] * v2[1];
        crossProduct[1] = v1[2] * v2[0] - v1[0] * v2[2];
        crossProduct[2] = v1[0] * v2[1] - v1[1] * v2[0];
    }

    public static void Main(string[] args)
    {
        // Point from which we need to calculate the
        // distance
        int[] pointA = { 1, 4, -2 };

        // Points on the line P
        int[] pointB = { 3, 1, -2 };
        int[] pointC = { 6, -2, 1 };

        // Vector BA
        int[] vecBA = { pointA[0] - pointB[0],
                        pointA[1] - pointB[1],
                        pointA[2] - pointB[2] };

        // Vector BC
        int[] vecBC = { pointC[0] - pointB[0],
                        pointC[1] - pointB[1],
                        pointC[2] - pointB[2] };

        // Array to store the cross product
        int[] crossProduct = new int[3];

        // Calculate the cross product of vecBA and vecBC
        GetCrossProduct(vecBA, vecBC, crossProduct);

        // Variable to store the distance of point A from
        // line P
        double dist = GetMagnitude(crossProduct)
                      / GetMagnitude(vecBC);

        // Output the distance
        Console.WriteLine(dist);
    }
}
JavaScript
// Get the magnitude of a vector
const getMagnitude = (v) => {
  return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
};

// Calculate the cross product of two vectors v1 and v2
const getCrossProduct = (v1, v2, crossProduct) => {
  crossProduct[0] = v1[1] * v2[2] - v1[2] * v2[1];
  crossProduct[1] = v1[2] * v2[0] - v1[0] * v2[2];
  crossProduct[2] = v1[0] * v2[1] - v1[1] * v2[0];
};

// Main function
const main = () => {
  // Point from which we need to calculate the distance
  const pointA = [1, 4, -2];

  // Points on the line P
  const pointB = [3, 1, -2];
  const pointC = [6, -2, 1];

  // Vector BA
  const vecBA = [pointA[0] - pointB[0], pointA[1] - pointB[1], pointA[2] - pointB[2]];

  // Vector BC
  const vecBC = [pointC[0] - pointB[0], pointC[1] - pointB[1], pointC[2] - pointB[2]];

  // Vector to store the cross product
  const crossProduct = [0, 0, 0];
  getCrossProduct(vecBA, vecBC, crossProduct);

  // Distance of point A from line P
  const dist = getMagnitude(crossProduct) / getMagnitude(vecBC);

  console.log(dist);
};

main();

Output
2.16025




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

4. Intersection Point of two lines:

We can find the intersection point of two lines in 2D using parametric equations. Parametric equations are a way of representing a curve in terms of one or more parameters. For a line in 2D, we can use the following parametric equation:

=> r = a + td

where a is the starting point of the line, t is a real parameter, d is the direction vector for the line and r is a point on the line.

So, for the first line the parametric equation will be, r1 = a1 + t1d1 and for the second line the parametric equation will be, r2 = a2 + t2d2. We can further simplify the second equation:

=> r2 – a2 = t2d2

Taking Cross Product with d2 vector on both sides.
=> (r2 – a2) X d2 = 0

As the lines intersect at any point, the value of r1 and r2 will be same at that intersection point. So, by substituting the value of r1 in the above equation,
=> (a1 + t1d1 – a2) X d2 = 0
=> t1 = ((a2 – a1) X d2) / (d1 X d2)

Now, we can find the intersection point by putting the value of t1 into r1 = a1 + t1d1

Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Since the product of 2D(x, y) vectors is a vector in z
// direction, we simply return the magnitude of the vector
double getCrossProduct(vector<double> v1, vector<double> v2)
{
    return v1[0] * v2[1] - v1[1] * v2[0];
}

vector<double> getDifference(vector<double> v1,
                            vector<double> v2)
{
    vector<double> diff(2);
    diff[0] = v2[0] - v1[0];
    diff[1] = v2[1] - v1[1];
    return diff;
}

vector<double> getSum(vector<double> v1, vector<double> v2)
{
    vector<double> sum(2);
    sum[0] = v1[0] + v2[0];
    sum[1] = v1[1] + v2[1];
    return sum;
}

int main()
{
    // Points of lines
    vector<double> pointA = { 1, 1 };
    vector<double> pointB = { 4, 4 };
    vector<double> pointC = { 1, 8 };
    vector<double> pointD = { 2, 4 };

    // direction vector d1
    vector<double> d1 = getDifference(pointA, pointB);
    // direction vector d2
    vector<double> d2 = getDifference(pointC, pointD);
    double t1
        = getCrossProduct(getDifference(pointA, pointC), d2)
        / (getCrossProduct(d1, d2) * 1.0);
    d1[0] *= t1;
    d1[1] *= t1;
    // Now, we can find the intersection point by putting
    // the value of t1 into r1 = A + t1d1
    vector<double> intersectionPoint = getSum(pointA, d1);

    cout << intersectionPoint[0] << " "
        << intersectionPoint[1];

    return 0;
}
Java
import java.util.*;

public class Main {
    // Since the product of 2D(x, y) vectors is a vector in z
    // direction, we simply return the magnitude of the vector
    public static double getCrossProduct(double[] v1, double[] v2) {
        return v1[0] * v2[1] - v1[1] * v2[0];
    }

    public static double[] getDifference(double[] v1, double[] v2) {
        double[] diff = new double[2];
        diff[0] = v2[0] - v1[0];
        diff[1] = v2[1] - v1[1];
        return diff;
    }

    public static double[] getSum(double[] v1, double[] v2) {
        double[] sum = new double[2];
        sum[0] = v1[0] + v2[0];
        sum[1] = v1[1] + v2[1];
        return sum;
    }

    public static void main(String[] args) {
        // Points of lines
        double[] pointA = { 1, 1 };
        double[] pointB = { 4, 4 };
        double[] pointC = { 1, 8 };
        double[] pointD = { 2, 4 };

        // direction vector d1
        double[] d1 = getDifference(pointA, pointB);
        // direction vector d2
        double[] d2 = getDifference(pointC, pointD);
        double t1 = getCrossProduct(getDifference(pointA, pointC), d2) / getCrossProduct(d1, d2);
        d1[0] *= t1;
        d1[1] *= t1;
        // Now, we can find the intersection point by putting
        // the value of t1 into r1 = A + t1d1
        double[] intersectionPoint = getSum(pointA, d1);

        System.out.println(intersectionPoint[0] + " " + intersectionPoint[1]);
    }
}
Python3
from typing import List

# Since the product of 2D(x, y) vectors is a vector in z
# direction, we simply return the magnitude of the vector
def getCrossProduct(v1: List[float], v2: List[float]) -> float:
    return v1[0] * v2[1] - v1[1] * v2[0]

def getDifference(v1: List[float], v2: List[float]) -> List[float]:
    diff = [0.0, 0.0]
    diff[0] = v2[0] - v1[0]
    diff[1] = v2[1] - v1[1]
    return diff

def getSum(v1: List[float], v2: List[float]) -> List[float]:
    sum = [0.0, 0.0]
    sum[0] = v1[0] + v2[0]
    sum[1] = v1[1] + v2[1]
    return sum

# Points of lines
pointA = [1, 1]
pointB = [4, 4]
pointC = [1, 8]
pointD = [2, 4]

# direction vector d1
d1 = getDifference(pointA, pointB)
# direction vector d2
d2 = getDifference(pointC, pointD)
t1 = getCrossProduct(getDifference(pointA, pointC), d2) / getCrossProduct(d1, d2)
d1[0] *= t1
d1[1] *= t1
# Now, we can find the intersection point by putting
# the value of t1 into r1 = A + t1d1
intersectionPoint = getSum(pointA, d1)

print(intersectionPoint[0], intersectionPoint[1])
JavaScript
// Function to calculate the cross product of two 2D vectors
function getCrossProduct(v1, v2) {
    return v1[0] * v2[1] - v1[1] * v2[0];
}

// Function to calculate the difference between two 2D vectors
function getDifference(v1, v2) {
    return [v2[0] - v1[0], v2[1] - v1[1]];
}

// Function to calculate the sum of two 2D vectors
function getSum(v1, v2) {
    return [v1[0] + v2[0], v1[1] + v2[1]];
}

// Main function
function main() {
    // Points of lines
    const pointA = [1, 1];
    const pointB = [4, 4];
    const pointC = [1, 8];
    const pointD = [2, 4];

    // Direction vector d1
    const d1 = getDifference(pointA, pointB);
    // Direction vector d2
    const d2 = getDifference(pointC, pointD);

    // Calculate t1
    const t1 = getCrossProduct(getDifference(pointA, pointC), d2) / getCrossProduct(d1, d2);

    // Calculate the scaled direction vector d1
    const scaledD1 = [d1[0] * t1, d1[1] * t1];

    // Calculate the intersection point by adding the scaled direction vector to pointA
    const intersectionPoint = getSum(pointA, scaledD1);

    // Output the intersection point
    console.log(intersectionPoint[0] + " " + intersectionPoint[1]);
}

// Invoke the main function
main();

Output
2.4 2.4




Click here to know about finding the intersection point using equation of lines.

Practice Problems on Basic Geometry for Competitive Programming:

Problem

Problem Link

Check if two line segments intersect

Practice Now

Line Passing through two points

Practice Now

Find the missing point of parallelogram

Practice Now



Similar Reads

Tips and Tricks for Competitive Programmers | Set 2 (Language to be used for Competitive Programming)
This is a question asked quite often as in which language should be preferred to be efficient in competitive programming. It is something one should not worry about as what matters is the logic, not the language. Most of the languages are more or less same, but till now the most preferred language is C++, and here are the reasons. Python Simple and
5 min read
Computational Geometry - Algorithms for Geometry
Computational geometry is a field of study that focuses on developing algorithms and data structures for solving problems that involve geometric shapes and structures. The field has applications in a variety of areas, including computer graphics, robotics, geographic information systems, and more. In this article, we will explore some of the key co
15+ min read
Competitive Programming vs General Programming
Programming enthusiasts face a crossroads - Competitive Programming or General Programming? This article sheds light on the distinctions between Competitive Programming vs General Programming, offering a quick guide for those navigating the coding landscape. Whether you're aiming for speed and precision in competitions or tackling real-world projec
3 min read
Dynamic Programming in Game Theory for Competitive Programming
In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive edge. Whether you're a seasoned coder or a newcomer
15+ min read
Top Programming Languages For Competitive Programming
Building an application, running a server, or even implementing a game needs a programming language as the foundation. There are almost more than 700 programming languages which are the most popular ones and this number will increase day by day. But, you don't need to learn all of them. Having a good command of anyone is enough for you to grow your
13 min read
Basic Geometry Formulas
In mathematics, geometry stands as a discipline of study and is a subject for the analysis of shapes and structures along with their properties. Geometry formulas are used for finding dimensions, perimeter, area, surface area, volume, etc. of the geometric shapes. The article below illustrates the standard and derived formulas of geometry for the c
8 min read
How to read Competitive Programming Questions?
Competitive Programming is considered as a sport in the field of computer science. The culture of this sport is growing day by day and a lot of people are also considering this as a career choice. So, to help the participants with improving their efficiency in this sport, in this post, we have tried to cover all possible things, needed to keep in m
5 min read
Some useful C++ tricks for beginners in Competitive Programming
Here are some of the basic C++ tricks that every beginner in Competitive Programming should follow for increased speed. However, competitive programming can only be mastered with time and lots of practice. These tricks will just help you to save a little time during the contests which sometimes matters a lot. Using the auto keyword to declare data
3 min read
Importance of Testing In Competitive Programming
Many times while solving problems, we face issues like time limit exceeds, wrong solution, runtime error, and memory limit exceeds because after designing algorithm we don't test algorithm efficiency, correctness, time complexity and running the algorithm on a large set of inputs for testing purpose. This is where stress testing comes for rescue. S
3 min read
Writing code faster during Competitive Programming in C++
This article focuses on how to implement your solutions and implement them fast while doing competitive programming. Setup Please refer Setting up a C++ Competitive Programming Environment Snippets Snippet is a programming term for a small region of re-usable source Code. A lot of modern text editors like Sublime provide you a functionality to auto
3 min read
Mathematics Tricks For Competitive Programming In Python 3
Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented fro
3 min read
5 Best Languages for Competitive Programming
Needless to say, Competitive Programming is one of the most crucial and popular aspects of a programmer's journey. Though, all the programmers are strongly recommended to participate in such coding challenges to enhance their coding skills and to get various ravishing prizes, rewards, and other career opportunities. Meanwhile, there's a question th
5 min read
Fast I/O for Competitive Programming in Python
In Competitive Programming, it is important to read input as fast as possible to save valuable time. Input/Output in Python can be sometimes time taking in cases when the input is huge or to output any numbers of lines or a huge number of arrays(lists) line after line. Fast Input Normally, the input is taken from STDIN in the form of String using i
3 min read
How to get started with Competitive Programming in JavaScript
Competitive programming is a popular activity among programmers looking to enhance their problem-solving skills and algorithmic thinking. JavaScript is a wonderful language for competitive programming because of how simple it is to use, how powerful its libraries are, and how quickly it can prototype ideas. JavaScript is a great option for programm
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Points to focus on while doing Competitive Programming
Competitive Programming is vital for one’s development in the coding field. This article is going to discuss some basics points one should keep in mind while competing. Make a list of functions to perform tasks that are encountered frequently in questions and add them to your code in the form of a template. This saves time during contests and helps
5 min read
How to Use int as long long int for Competitive Programming?
Most of the time, input constraints in Competitive programming questions are bigger than the limits of int. Therefore, there is a need to use long int or even long long int. Here let us take two cases so that if a naive user writes correct logic still input is not getting accepted can get to know where the rectification is required. Case 1: Big int
3 min read
Java Generics to Code Efficiently in Competitive Programming
Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader a
9 min read
Setting up Java Competitive Programming Environment
An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, run
5 min read
Creation and Utilisation of Custom Snippets for Competitive programming in VScode
Coding down the whole algorithm from scratch during the online contest can cost you plenty of time and may lead to a bad rank. There is no point in coding the same algorithm you have coded hundreds of times earlier. Why not utilize your previously coded implementations? You can do that by creating custom code snippets and summoning them just by a k
2 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Most Critical Mistakes & Tips in Competitive Programming
The moment a beginner hears this word, an image pops up in one's mind where students are sitting in a room full of Computers and coding some out of the world stuff, We'll to be honest it's nothing too hard to grasp so we will be proposing tips that help a programmer to level up faster. So let's begin with the most underrated points on each topic wh
15+ min read
What are Ad Hoc Problems in Competitive Programming?
The Ad Hoc problems are problems that cannot be classified anywhere else in the categories with well-studied solutions since each problem description and its corresponding solution are unique. These problems don't fall under standard categories, there is no specific or general technique exists to solve them. Many Ad Hoc problems are easy, but this
5 min read
Is Competitive Programming Must For Software Development Roles?
Competitive Programming is a mental sport that involves programmers competing against each other within the given time limit. It makes your problem-solving and coding skills better and efficient - also, it provides you with an edge over other candidates during the tech interviews. It makes you an amazing problem solver which is important in softwar
5 min read
What are Online and Offline query-based questions in Competitive Programming
The query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element set before printing the result. Features: Offline
4 min read
Top 10 Most Used Inbuilt C++ functions for Competitive Programming
In this article, we will discuss about the 10 most used inbuilt functions of C++ which will help you to save time and make code concise as well during competitive programming. List of top 10 inbuilt functions in C++ pow()sqrt()min()max()swap()gcd()toupper()tolower()floor()ceil()1. pow( ) This function helps to find the value of a number raised to a
7 min read
Setting up Sublime Text For Competitive Programming (C++) Using Fast Olympic Coding Plugin
Competitive Programming is a mind sport where time matters the most. For that, a fast and easy-to-use tool is required for writing code. Sublime text along with the CppFastOlympicCoding plugin provides the same. Sublime text is popular for its fast performance and aesthetic UI. The CppFastOlympicCoding plugin offers features such as: TestManager: W
4 min read
How to Setup IntelliJ IDEA For Java Competitive Programming Environment?
IntelliJ IDEA is a popular Integrated Development Environment (IDE) used by many developers for Java programming. In this article, we'll walk through the steps to set up IntelliJ IDEA for competitive programming. Competitive programming is a popular activity among computer science students and professionals, as it provides an opportunity to test th
4 min read
Interactive Problems in Competitive Programming | Set 2
Introduction to interactive problems in competitive programming is already discussed in the previous article. In this article, another problem based on the same concept is discussed. Assume that the judge has a hidden (it means the user can't access it) sorted array. The user (i.e. you) need to tell whether a given element VAL lies in that sorted a
3 min read
Getting Started with Competitive Programming in Python
Python is a great option for programming in Competitive Programming. First off, its easy-to-understand and concise grammar enables quicker development and simpler debugging. The huge standard library of Python offers a wide range of modules and functions that can be used to effectively address programming difficulties. Python also offers dynamic ty
11 min read
three90RightbarBannerImg