Skip to content

Commit 8daa8a4

Browse files
Sushant NadavadeSushant Nadavade
authored andcommitted
all issues are resolved
1 parent 091f57d commit 8daa8a4

File tree

1 file changed

+35
-12
lines changed

1 file changed

+35
-12
lines changed

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

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -138,17 +138,41 @@ public static double computeWidth(Collection<Point> points) {
138138
int n = hull.size();
139139
double minWidth = Double.MAX_VALUE;
140140

141-
// Use rotating calipers to find minimum width
141+
// Check all orientations defined by pairs of hull points
142+
// This ensures we find the true minimum width
142143
for (int i = 0; i < n; i++) {
143-
Point p1 = hull.get(i);
144-
Point p2 = hull.get((i + 1) % n);
145-
146-
// Find the antipodal point for this edge
147-
int j = findAntipodalPoint(hull, i);
148-
149-
// Compute width as distance between parallel lines
150-
double width = distanceToLine(p1, p2, hull.get(j));
151-
minWidth = Math.min(minWidth, width);
144+
for (int j = i + 1; j < n; j++) {
145+
Point p1 = hull.get(i);
146+
Point p2 = hull.get(j);
147+
148+
// Calculate direction vector
149+
double dx = p2.x() - p1.x();
150+
double dy = p2.y() - p1.y();
151+
double len = Math.sqrt(dx * dx + dy * dy);
152+
153+
if (len == 0) continue;
154+
155+
// Unit direction vector
156+
double unitX = dx / len;
157+
double unitY = dy / len;
158+
159+
// Perpendicular unit vector
160+
double perpX = -unitY;
161+
double perpY = unitX;
162+
163+
// Project all points onto the perpendicular direction
164+
double minProj = Double.MAX_VALUE;
165+
double maxProj = Double.MIN_VALUE;
166+
167+
for (Point p : hull) {
168+
double proj = p.x() * perpX + p.y() * perpY;
169+
minProj = Math.min(minProj, proj);
170+
maxProj = Math.max(maxProj, proj);
171+
}
172+
173+
double width = maxProj - minProj;
174+
minWidth = Math.min(minWidth, width);
175+
}
152176
}
153177

154178
return minWidth;
@@ -292,8 +316,7 @@ private static List<Point> ensureCounterClockwiseOrder(List<Point> hull) {
292316
for (int i = 1; i < hull.size(); i++) {
293317
Point current = hull.get(i);
294318
// Check if current point is better than current best
295-
boolean isBetter = current.y() < bottomMost.y()
296-
|| (current.y() == bottomMost.y() && current.x() < bottomMost.x());
319+
boolean isBetter = current.y() < bottomMost.y() || (current.y() == bottomMost.y() && current.x() < bottomMost.x());
297320

298321
if (isBetter) {
299322
bottomMost = current;

0 commit comments

Comments
 (0)