Skip to content

Commit ca16e4e

Browse files
Add Rotating Calipers algorithm implementation
Implement Rotating Calipers algorithm to find the farthest pair of points in a convex polygon.
1 parent 3688fef commit ca16e4e

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.thealgorithms.geometry;
2+
3+
import java.util.List;
4+
5+
/**
6+
* Rotating Calipers algorithm to find the farthest pair of points (diameter)
7+
* from a convex polygon.
8+
*
9+
* Time Complexity: O(n)
10+
*
11+
* Reference: https://cp-algorithms.com/geometry/rotating_calipers.html
12+
*/
13+
public final class RotatingCalipers {
14+
private RotatingCalipers() {}
15+
16+
public static double findDiameter(List<Point> points) {
17+
int n = points.size();
18+
if (n < 2) return 0;
19+
20+
int j = 1;
21+
double maxDist = 0;
22+
23+
for (int i = 0; i < n; i++) {
24+
Point nextI = points.get((i + 1) % n);
25+
while (Point.cross(nextI.subtract(points.get(i)), points.get((j + 1) % n).subtract(points.get(j))) > 0) {
26+
j = (j + 1) % n;
27+
}
28+
maxDist = Math.max(maxDist, points.get(i).distance(points.get(j)));
29+
}
30+
31+
return maxDist;
32+
}
33+
}

0 commit comments

Comments
 (0)