Number of possible Triangles in a Cartesian coordinate system - GeeksforGeeks
Given n points in a Cartesian coordinate system. Count the number of triangles formed.
Given n points in a Cartesian coordinate system. Count the number of triangles formed.
A simple solution is to check if the determinant of the three points selected is non-zero or not. The following determinant gives the area of a Triangle (Also known as Cramer’s rule).
Area of the triangle with corners at (x1, y1), (x2, y2) and (x3, y3) is given by:
We can solve this by taking all possible combination of 3 points and finding the determinant.
// Returns determinant value of three points in 2D
int
det(
int
x1,
int
y1,
int
x2,
int
y2,
int
x3,
int
y3)
{
return
x1*(y2 - y3) - y1*(x2 - x3) + 1*(x2*y3 - y2*x3);
}
// Returns count of possible triangles with given array
// of points in 2D.
int
countPoints(Point arr[],
int
n)
{
int
result = 0;
// Initialize result
// Consider all triplets of points given in inputs
// Increment the result when determinant of a triplet
// is not 0.
for
(
int
i=0; i<n; i++)
for
(
int
j=i+1; j<n; j++)
for
(
int
k=j+1; k<n; k++)
if
(det(arr[i].x, arr[i].y, arr[j].x,
arr[j].y, arr[k].x, arr[k].y))
result++;
return
result;
}
The complexity of the above solution code is O(n3).
Optimization :
We can optimize above solution to work in O(n2) using the fact that hree points cannot form a triangle if they are collinear. We can use hashing to store slopes of all pairs and find all triangles in O(n2) time.
Read full article from Number of possible Triangles in a Cartesian coordinate system - GeeksforGeeksWe can optimize above solution to work in O(n2) using the fact that hree points cannot form a triangle if they are collinear. We can use hashing to store slopes of all pairs and find all triangles in O(n2) time.