Skip to content

Commit a2ada7c

Browse files
author
motalib-code
committed
Fix diameter algorithm to check all point pairs
1 parent 25f7b1f commit a2ada7c

File tree

1 file changed

+6
-24
lines changed

1 file changed

+6
-24
lines changed

src/main/java/com/thealgorithms/geometry/RotatingCalipers.java

Lines changed: 6 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -85,34 +85,16 @@ public static PointPair diameter(List<Point> convexHull) {
8585
return new PointPair(convexHull.get(0), convexHull.get(1));
8686
}
8787

88-
int n = convexHull.size();
88+
// Find maximum distance between all pairs of points
8989
PointPair maxPair = new PointPair(convexHull.get(0), convexHull.get(1));
9090

91-
int j = 1;
92-
for (int i = 0; i < n; i++) {
93-
Point p1 = convexHull.get(i);
94-
Point p2 = convexHull.get((i + 1) % n);
95-
96-
// Find the farthest point from edge p1-p2
97-
while (true) {
98-
int nextJ = (j + 1) % n;
99-
if (distanceToLine(p1, p2, convexHull.get(nextJ)) > distanceToLine(p1, p2, convexHull.get(j))) {
100-
j = nextJ;
101-
} else {
102-
break;
91+
for (int i = 0; i < convexHull.size(); i++) {
92+
for (int j = i + 1; j < convexHull.size(); j++) {
93+
PointPair candidate = new PointPair(convexHull.get(i), convexHull.get(j));
94+
if (candidate.distance > maxPair.distance) {
95+
maxPair = candidate;
10396
}
10497
}
105-
106-
// Check distances from current edge endpoints to the farthest point
107-
PointPair candidate1 = new PointPair(p1, convexHull.get(j));
108-
PointPair candidate2 = new PointPair(p2, convexHull.get(j));
109-
110-
if (candidate1.distance > maxPair.distance) {
111-
maxPair = candidate1;
112-
}
113-
if (candidate2.distance > maxPair.distance) {
114-
maxPair = candidate2;
115-
}
11698
}
11799

118100
return maxPair;

0 commit comments

Comments
 (0)