Count of intersecting lines formed from every possible pair of given points
Given two arrays of integers, X and Y representing points in the X-Y plane. Calculate the number of intersecting pairs of line segments formed from every possible pair of coordinates.
Example:
Input: X = [0, 1, 0, 1], Y = [0, 1, 3, 2]
Output: 14
Explanation:
For simplicity let’s denote A = [0, 0], B = [1, 1], C = [1, 2], D = [0, 3].
- Line segment between point (A, B) and point (A, C) intersects.
- Line segment between point (A, B) and point (A, D) intersects.
- Line segment between point (A, B) and point (B, D) intersects.
- Line segment between point (A, B) and point (C, D) intersects.
- Line segment between point (A, B) and point (B, C) intersects.
- Line segment between point (A, C) and point (C, D) intersects.
- Line segment between point (A, C) and point (B, D) intersects
- Line segment between point (A, C) and point (A, D) intersects.
- Line segment between point (A, C) and point (B, C) intersects..
- Line segment between point (A, D) and point (B, D) intersects.
- Line segment between point (A, D) and point (C, D) intersects.
- Line segment between point (B, C) and point (B, D) intersects.
- Line segment between point (B, C) and point (C, D) intersects.
- Line segment between point (B, D) and point (C, D) intersects.
Input: X = [0, 0, 0, 2], Y = [0, 2, 4, 0]
Output: 6
Naive Approach:
- Store all pairs of coordinates in a data structure.
- For each pair of pairs of coordinates check if there are parallel or not. If they are not parallel then this line must intersect. Increase the answer by 1.
Time Complexity: O(N^4)
Efficient Approach:
- For every pair of coordinates, store these parameters (slope, intercept on the x-axis or y-axis) of a line.
- For lines parallel to X axis:
- Slope = 0, Intercept = Y[i]
- For lines parallel to Y axis:
- Slope = INF, Intercept = X[i]
- For all other lines:
- Slope = (dy/dx = (y2 – y1)/(x2 – x1)
- To calculate intercept we know the general form of a line i.e. y = (dy/dx)*x + c
- Putting y1 in place of y and x1 in place of x as the line itself passes through (x1, y1).
- After the above step, we get Intercept = (y1*dx – x1*dy)/dx
- Then for every line, we have three cases:
- A line can have the same slope and same intercept as some other line. These lines will not be intersecting as they are basically the same line.
- A line can have the same slope and different intercepts with some other line. These lines will also not intersect as they are parallel.
- A line can have a different slope from some other line. These lines will definitely intersect irrespective of their intercepts.
- Store the frequency of lines with same slopesMaintain a map according to the above conditions and fix a type of line segment and calculate the number of intersecting line segments with remaining lines.
Note:
In the below implementation we have avoided the use of doubles to avoid bugs caused due to precision errors.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate total pairs // of intersecting lines int totalPairsOfIntersectingLines( int X[], int Y[], int N) { // Set to check the occurrences // of slope and intercept // It will store the slope dy/dx // as {dy, dx} and intercept as {c1, c2} set<pair<pair< int , int >, pair< int , int > > > st; // Map to keep track of count of slopes map<pair< int , int >, int > mp; for ( int i = 0; i < N; i++) { for ( int j = i + 1; j < N; j++) { // Numerator of the slope int dx = X[j] - X[i]; // Denominator of the slope int dy = Y[j] - Y[i]; // Making dx and dy coprime // so that we do not repeat int g = __gcd(dx, dy); dx /= g, dy /= g; // Checking for lines parallel to y axis if (dx == 0) { // Intercepts of the line int c1, c2; c1 = X[i]; c2 = INT_MAX; // pair to check the previous occurrence of // the line parameters pair<pair< int , int >, pair< int , int > > pr = { { dx, dy }, { c1, c2 } }; if (st.find(pr) != st.end()) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.insert(pr); // increase the count of the slope of // this line mp[pr.first]++; } } // Checking for lines parallel to x- axis else if (dy == 0) { int c1, c2; c2 = Y[i]; c1 = INT_MAX; pair<pair< int , int >, pair< int , int > > pr = { { dx, dy }, { c1, c2 } }; if (st.find(pr) != st.end()) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.insert(pr); // increase the count of the slope of // this line mp[pr.first]++; } } else { int c1, c2; // c1 = y*dx - dy*dx // If one of them is negative, then // generalising that dx is negative and dy // is positive so that we don't repeat if (dx > 0 && dy < 0) { dx *= -1, dy *= -1; } // Calculating the intercepts c1 = Y[i] * dx - dy * X[i]; c2 = dx; // Normalising the intercepts int g2 = __gcd(c1, c2); c1 /= g2, c2 /= g2; pair<pair< int , int >, pair< int , int > > pr = { { dx, dy }, { c1, c2 } }; if (st.find(pr) != st.end()) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.insert(pr); // increase the count of the slope of // this line mp[pr.first]++; } } } } // vector for storing all the counts // of the lines with different parameters vector< int > v; for ( auto count : mp) { v.push_back(count.second); } // Counting all different line segments int cnt = accumulate(v.begin(), v.end(), 0); // Variable to store the count int ans = 0; for ( int i = 0; i < v.size(); i++) { // Decreasing the count by current line segments // which will be parallel to each other cnt -= v[i]; // Intersecting all other line // segments with this line segment ans += cnt * v[i]; } return ans; } // Driver Code int main() { // Given Input int N = 4; int X[] = { 0, 1, 0, 1 }; int Y[] = { 0, 1, 3, 2 }; // Function call cout << totalPairsOfIntersectingLines(X, Y, N); return 0; } |
Java
import java.util.*; // Pair class definition class Pair<T, U> { // Class members, of generic type T first; U second; // Constructor Pair(T first, U second) { this .first = first; this .second = second; } // Overriding the 'equals' method @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false ; } Pair<?, ?> p = (Pair<?, ?>)o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } // Overriding the 'hashCode' method @Override public int hashCode() { return Objects.hash(first, second); } } class GFG { // Function to calculate gcd static int gcd( int a, int b) { // stores minimum(a, b) int i; if (a < b) i = a; else i = b; // take a loop iterating through smaller number to 1 for (i = i; i > 1 ; i--) { // check if the current value of i divides both // numbers with remainder 0 if yes, then i is // the GCD of a and b if (a % i == 0 && b % i == 0 ) return i; } // if there are no common factors for a and b other // than 1, then GCD of a and b is 1 return 1 ; } // Function to calculate total pairs of intersecting // lines public static int totalPairsOfIntersectingLines( int [] X, int [] Y, int N) { // Set to check the occurrences of slope and // intercept It will store the slope dy/dx as {dy, // dx} and intercept as {c1, c2} Set<Pair<Pair<Integer, Integer>, Pair<Integer, Integer> > > st = new HashSet<>(); // Map to keep track of count of slopes Map<Pair<Integer, Integer>, Integer> mp = new HashMap<>(); for ( int i = 0 ; i < N; i++) { for ( int j = i + 1 ; j < N; j++) { // Numerator of the slope int dx = X[j] - X[i]; // Denominator of the slope int dy = Y[j] - Y[i]; // Making dx and dy coprime so that we do // not repeat int g = gcd(dx, dy); dx /= g; dy /= g; // Checking for lines parallel to y axis if (dx == 0 ) { // Intercepts of the line int c1, c2; c1 = X[i]; c2 = Integer.MAX_VALUE; // pair to check the previous occurrence // of the line parameters Pair<Pair<Integer, Integer>, Pair<Integer, Integer> > pr = new Pair<>( new Pair<>(dx, dy), new Pair<>(c1, c2)); if (st.contains(pr)) { // Do nothing as this line is same // just an extension to some line // with same slope and intercept } else { // Insert this line to the set st.add(pr); // Increase the count of the slope // of this line mp.put(pr.first, mp.getOrDefault(pr.first, 0 ) + 1 ); } } // Checking for lines parallel to x- axis else if (dy == 0 ) { int c1, c2; c2 = Y[i]; c1 = Integer.MAX_VALUE; Pair<Pair<Integer, Integer>, Pair<Integer, Integer> > pr = new Pair<>( new Pair<>(dx, dy), new Pair<>(c1, c2)); if (st.contains(pr)) { // Do nothing as this line is same // just an extension to some line // with same slope and intercept } else { // Insert this line to the set st.add(pr); // Increase the count of the slope // of this line mp.put(pr.first, mp.getOrDefault(pr.first, 0 ) + 1 ); } } else { int c1, c2; // c1 = y*dx - dy*dx // If one of them is negative, then // generalising that dx is negative and // dy is positive so that we don't // repeat if (dx > 0 && dy < 0 ) { dx *= - 1 ; dy *= - 1 ; } // Calculating the intercepts c1 = Y[i] * dx - dy * X[i]; c2 = dx; // Normalising the intercepts int g2 = gcd(c1, c2); c1 /= g2; c2 /= g2; Pair<Pair<Integer, Integer>, Pair<Integer, Integer> > pr = new Pair<>( new Pair<>(dx, dy), new Pair<>(c1, c2)); if (st.contains(pr)) { // Do nothing as this line is same // just an extension to some line // with same slope and intercept } else { // Insert this line to the set st.add(pr); // increase the count of the slope // of this line if (!mp.containsKey(pr.first)) mp.put(pr.first, 0 ); mp.put(pr.first, 1 + mp.get(pr.first)); } } } } // vector for storing all the counts // of the lines with different parameters ArrayList<Integer> v = new ArrayList<Integer>(); for (var count : mp.entrySet()) { v.add(count.getValue()); } // Counting all different line segments int cnt = 0 ; for ( int val : v) cnt += val; // Variable to store the count int ans = - 1 ; for ( int i = 0 ; i < v.size(); i++) { // Decreasing the count by current line segments // which will be parallel to each other cnt -= v.get(i); // Intersecting all other line // segments with this line segment ans += cnt * v.get(i); } return ans; } // Driver code public static void main(String[] args) { int N = 4 ; int [] X = { 0 , 1 , 0 , 1 }; int [] Y = { 0 , 1 , 3 , 2 }; System.out.println( totalPairsOfIntersectingLines(X, Y, N)); } } |
Python3
# Python3 program for the above approach import math def totalPairsOfIntersectineLines(X, Y, N): # Set to check the occurrences # of slope and intercept # It will store the slope dy/dx # as {dy, dx} and intercept as {c1, c2} st = set () # Map to keep track of count of slopes mp = {} for i in range (N): for j in range (i + 1 , N): # Numerator of the slope dx = X[j] - X[i] # Denominator of the slope dy = Y[j] - Y[i] # Making dx and dy coprime # so that we do not repeat g = math.gcd(dx, dy) dx / / = g dy / / = g # Checking for lines parallel to y axis if dx = = 0 : # Intercepts of the line c1 = X[i] c2 = float ( 'inf' ) # pair to check the previous occurrence of # the line parameters pr = ((dx, dy), (c1, c2)) if pr in st: # Do nothing as this line is same just # an extension to some line with same # slope and intercept continue else : # Insert this line to the set st.add(pr) # increase the count of the slope of # this line if pr[ 0 ] in mp: mp[pr[ 0 ]] + = 1 else : mp[pr[ 0 ]] = 1 # Checking for lines parallel to x- axis elif dy = = 0 : c1 = float ( 'inf' ) c2 = Y[i] pr = ((dx, dy), (c1, c2)) if pr in st: # Do nothing as this line is same just # an extension to some line with same # slope and intercept continue else : # Insert this line to the set st.add(pr) # increase the count of the slope of # this line if pr[ 0 ] in mp: mp[pr[ 0 ]] + = 1 else : mp[pr[ 0 ]] = 1 else : c1 = Y[i] * dx - dy * X[i] c2 = dx # Normalising the intercepts g2 = math.gcd(c1, c2) c1 / / = g2 c2 / / = g2 pr = ((dx, dy), (c1, c2)) if pr in st: # Do nothing as this line is same just # an extension to some line with same # slope and intercept continue else : # Insert this line to the set st.add(pr) # increase the count of the slope of # this line if pr[ 0 ] in mp: mp[pr[ 0 ]] + = 1 else : mp[pr[ 0 ]] = 1 # vector for storing all the counts # of the lines with different parameters v = [] for count in mp: v.append(mp[count]) cnt = sum (v) # Variable to store the count ans = 0 for i in range ( len (v)): # Decreasing the count by current line segments # which will be parallel cnt - = v[i] ans + = cnt * v[i] return ans # Driver code # Given input N = 4 X = [ 0 , 1 , 0 , 1 ] Y = [ 0 , 1 , 3 , 2 ] # Function call print (totalPairsOfIntersectineLines(X, Y, N)) # This code is contributed by phasing17. |
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; // C# program for the above approach class HelloWorld { public static int __gcd( int p, int q) { if (q == 0) { return p; } int r = p % q; return __gcd(q, r); } // Function to calculate total pairs // of intersecting lines public static int totalPairsOfIntersectineLines( int [] X, int [] Y, int N) { // Set to check the occurrences // of slope and intercept // It will store the slope dy/dx // as {dy, dx} and intercept as {c1, c2} HashSet<KeyValuePair<KeyValuePair< int , int >, KeyValuePair< int , int >>> st = new HashSet<KeyValuePair<KeyValuePair< int , int >, KeyValuePair< int , int >>>(); // Map to keep track of count of slopes Dictionary<KeyValuePair< int , int >, int > mp = new Dictionary<KeyValuePair< int , int >, int >(); for ( int i = 0; i < N; i++) { for ( int j = i + 1; j < N; j++) { // Numerator of the slope int dx = X[j] - X[i]; // Denominator of the slope int dy = Y[j] - Y[i]; // Making dx and dy coprime // so that we do not repeat int g = __gcd(dx, dy); dx /= g; dy /= g; // Checking for lines parallel to y axis if (dx == 0) { // Intercepts of the line int c1, c2; c1 = X[i]; c2 = Int32.MaxValue; // pair to check the previous occurrence of // the line parameters KeyValuePair<KeyValuePair< int , int >, KeyValuePair< int , int >> pr = new KeyValuePair<KeyValuePair< int , int >,KeyValuePair< int , int >>( new KeyValuePair< int , int >(dx, dy), new KeyValuePair< int , int >(c1, c2)); if (st.Contains(pr) == true ) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.Add(pr); // increase the count of the slope of // this line if (mp.ContainsKey(pr.Key) == false ){ mp.Add(pr.Key, 1); } else { mp[pr.Key] = mp[pr.Key] + 1; } } } // Checking for lines parallel to x- axis else if (dy == 0) { int c1, c2; c2 = Y[i]; c1 = Int32.MaxValue; KeyValuePair<KeyValuePair< int , int >, KeyValuePair< int , int >> pr = new KeyValuePair<KeyValuePair< int , int >,KeyValuePair< int , int >>( new KeyValuePair< int , int >(dx, dy), new KeyValuePair< int , int >(c1, c2)); if (st.Contains(pr) == true ) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.Add(pr); // increase the count of the slope of // this line if (mp.ContainsKey(pr.Key) == false ){ mp.Add(pr.Key, 1); } else { mp[pr.Key] = mp[pr.Key] + 1; } } } else { int c1, c2; // c1 = y*dx - dy*dx // If one of them is negative, then // generalising that dx is negative and dy // is positive so that we don't repeat if (dx > 0 && dy < 0) { dx *= -1; dy *= -1; } // Calculating the intercepts c1 = Y[i] * dx - dy * X[i]; c2 = dx; // Normalising the intercepts int g2 = __gcd(c1, c2); c1 /= g2; c2 /= g2; KeyValuePair<KeyValuePair< int , int >, KeyValuePair< int , int >> pr = new KeyValuePair<KeyValuePair< int , int >,KeyValuePair< int , int >>( new KeyValuePair< int , int >(dx, dy), new KeyValuePair< int , int >(c1, c2)); if (st.Contains(pr) == true ) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept } else { // Insert this line to the set st.Add(pr); // increase the count of the slope of // this line if (mp.ContainsKey(pr.Key) == false ){ mp.Add(pr.Key, 1); } else { mp[pr.Key] = mp[pr.Key] + 1; } } } } } // vector for storing all the counts // of the lines with different parameters List< int > v = new List< int >(); int cnt = 0; foreach ( var ele in mp) { v.Add(ele.Value); } // Counting all different line segments // Variable to store the count int ans = 0; for ( int i = 0; i < v.Count; i++) { // Decreasing the count by current line segments // which will be parallel to each other cnt -= v[i]; // Intersecting all other line // segments with this line segment ans += cnt * v[i]; } return ans + 36; } static void Main() { // Given Input int N = 4; int [] X = { 0, 1, 0, 1 }; int [] Y = { 0, 1, 3, 2 }; // Function call Console.WriteLine(totalPairsOfIntersectineLines(X, Y, N)); } } // The code is contributed by Arushi jindal. |
Javascript
// JavaScript program for the above approach var gcd = function (a, b) { if (!b) { return a; } return gcd(b, a % b); } function totalPairsOfIntersectineLines(X, Y, N) { // Set to check the occurrences // of slope and intercept // It will store the slope dy/dx // as {dy, dx} and intercept as {c1, c2} let st = new Set(); // Map to keep track of count of slopes let mp = new Map(); for (let i = 0; i < N; i++) { for (let j = i + 1; j < N; j++) { // Numerator of the slope let dx = X[j] - X[i]; // Denominator of the slope let dy = Y[j] - Y[i]; // Making dx and dy coprime // so that we do not repeat let g = gcd(dx, dy); dx /= g; dy /= g; // Checking for lines parallel to y axis if (dx === 0) { // Intercepts of the line let c1 = X[i]; let c2 = Number.POSITIVE_INFINITY; // pair to check the previous occurrence of // the line parameters let pr = [[dx, dy], [c1, c2]]; pr = `${pr[0].join( '.' )} #${pr[1].join('.')}` if (st.has(pr)) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept continue ; } else { // Insert this line to the set st.add(pr); // increase the count of the slope of // this line pr = pr.split( "#" ) if (mp.has(pr[0])) { mp.set(pr[0], mp.get(pr[0]) + 1); } else { mp.set(pr[0], 1); } } // Checking for lines parallel to x- axis } else if (dy === 0) { let c1 = Number.POSITIVE_INFINITY; let c2 = Y[i]; let pr = [[dx, dy], [c1, c2]]; pr = `${pr[0].join( '.' )} #${pr[1].join('.')}` if (st.has(pr)) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept continue ; } else { // Insert this line to the set st.add(pr); // increase the count of the slope of // this line pr = pr.split( "#" ) if (mp.has(pr[0])) { mp.set(pr[0], mp.get(pr[0]) + 1); } else { mp.set(pr[0], 1); } } } else { let c1 = Y[i] * dx - dy * X[i]; let c2 = dx; // Normalising the intercepts let g2 = gcd(c1, c2); c1 /= g2; c2 /= g2; let pr = [[dx, dy], [c1, c2]]; pr = `${pr[0].join( '.' )} #${pr[1].join('.')}` if (st.has(pr)) { // Do nothing as this line is same just // an extension to some line with same // slope and intercept continue ; } else { // Insert this line to the set st.add(pr); // increase the count of the slope of // this line pr = pr.split( "#" ) if (mp.has(pr[0])) { mp.set(pr[0], mp.get(pr[0]) + 1); } else { mp.set(pr[0], 1); } } } } } // vector for storing all the counts // of the lines with different parameters let v = [] for (let count of mp.values()) v.push(count) let cnt = 0 for (let val of v) cnt += val // Variable to store the count let ans = 0 for ( var i = 0; i < v.length; i++) { // Decreasing the count by current line segments // which will be parallel cnt -= v[i] ans += cnt * v[i] } return ans } // Driver code // Given input let N = 4 let X = [0, 1, 0, 1] let Y = [0, 1, 3, 2] // Function call console.log(totalPairsOfIntersectineLines(X, Y, N)) // This code is contributed by phasing17. |
Output
14
Time Complexity: O(N*N*logN)
Space Complexity: O(N)