Given X and Y coordinates of N points on a Cartesian plane. The task is to find the number of possible triangles with the non-zero area that can be formed by joining each point to every other point. Examples:
A Naive approach has been already discussed in Number of possible Triangles in a Cartesian coordinate system 7Efficient Approach: Consider a point Z and find its slope with every other point. Now, if two points are having the same slope with point Z that means the 3 points are collinear and they cannot form a triangle. Hence, the number of triangles having Z as one of its points is the number of ways of choosing 2 points from the remaining points and then subtracting the number of ways of choosing 2 points from points having the same slope with Z. Since Z can be any point among N points, we have to iterate one more loop.
Steps to solve the problem:
Initialize an empty map mp and a variable ans to 0.
Iterate from 0 to N-1.
Clear the map mp.
For each point i, calculate the slope of all other points with respect to the current point.
calculate the greatest common divisor (GCD) of the difference in X and Y coordinate
between point i and j. Divide the difference in X and Y coordinates by their GCD.
Store the slope as a key-value pair in the map mp, where the key is a pair of integers representing the slope and the value is the frequency of that slope.
Calculate the number of ways by the formula (N – (i + 1)) * (N – (i + 1) – 1) / 2. Add this value to the and.
Iterate over the map mp, and for each key-value pair, calculate the number of ways by the formula j.second * (j.second – 1) /2.
Subtract this value from the and.
Return the final value of ans.
Below is the implementation of the above approach:
Please Login to comment...