forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotatingCalipers.java
More file actions
364 lines (297 loc) · 11.9 KB
/
RotatingCalipers.java
File metadata and controls
364 lines (297 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package com.thealgorithms.geometry;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* A class implementing the Rotating Calipers algorithm for geometric computations on convex polygons.
*
* The Rotating Calipers algorithm is an efficient technique for solving various geometric problems
* on convex polygons, including:
* - Computing the diameter (maximum distance between any two points)
* - Computing the width (minimum distance between parallel supporting lines)
* - Finding the minimum-area bounding rectangle
*
* Algorithm Description:
* 1. Compute the convex hull of the given points
* 2. Use rotating calipers (parallel lines) that rotate around the convex hull
* 3. For each rotation, compute the desired geometric property
* 4. Return the optimal result
*
* Time Complexity: O(n) where n is the number of points in the convex hull
* Space Complexity: O(n) for storing the convex hull
*
* Reference:
* Shamos, M. I. (1978). Computational Geometry.
*
* @author TheAlgorithms
*/
public final class RotatingCalipers {
private RotatingCalipers() {
}
/**
* Represents a pair of points with their distance.
*/
public record PointPair(Point p1, Point p2, double distance) {
@Override
public String toString() {
return String.format("PointPair(%s, %s, distance=%.2f)", p1, p2, distance);
}
}
/**
* Represents a rectangle with its area.
*/
public record Rectangle(Point bottomLeft, Point topRight, double area) {
@Override
public String toString() {
return String.format("Rectangle(%s, %s, area=%.2f)", bottomLeft, topRight, area);
}
}
/**
* Computes the diameter of a convex polygon using rotating calipers.
* The diameter is the maximum distance between any two points of the polygon.
*
* @param points List of points representing a convex polygon
* @return PointPair containing the two points with maximum distance and the distance
* @throws IllegalArgumentException if points is null or has less than 2 points
*/
public static PointPair computeDiameter(Collection<Point> points) {
if (points == null || points.size() < 2) {
throw new IllegalArgumentException("Points list must contain at least 2 points");
}
List<Point> hull = ConvexHull.convexHullRecursive(new ArrayList<>(points));
if (hull.size() < 2) {
throw new IllegalArgumentException("Convex hull must contain at least 2 points");
}
hull = ensureCounterClockwiseOrder(hull);
if (hull.size() == 2) {
Point p1 = hull.get(0);
Point p2 = hull.get(1);
return new PointPair(p1, p2, distance(p1, p2));
}
int n = hull.size();
PointPair maxPair = null;
double maxDistance = 0.0;
int j = 1;
// Rotating calipers algorithm requires indexed access for antipodal point tracking
for (int i = 0; i < n; i++) {
Point p1 = hull.get(i);
// Find antipodal point for current vertex
while (true) {
Point next = hull.get((j + 1) % n);
double dist1 = distance(p1, hull.get(j));
double dist2 = distance(p1, next);
if (dist2 > dist1) {
j = (j + 1) % n;
} else {
break;
}
}
double dist = distance(p1, hull.get(j));
if (dist > maxDistance) {
maxDistance = dist;
maxPair = new PointPair(p1, hull.get(j), dist);
}
}
return maxPair;
}
/**
* Computes the width of a convex polygon using rotating calipers.
* The width is the minimum distance between two parallel supporting lines.
*
* @param points List of points representing a convex polygon
* @return The minimum width of the polygon
* @throws IllegalArgumentException if points is null or has less than 2 points
*/
public static double computeWidth(Collection<Point> points) {
if (points == null || points.size() < 2) {
throw new IllegalArgumentException("Points list must contain at least 2 points");
}
List<Point> hull = ConvexHull.convexHullRecursive(new ArrayList<>(points));
if (hull.size() < 2) {
throw new IllegalArgumentException("Convex hull must contain at least 2 points");
}
hull = ensureCounterClockwiseOrder(hull);
if (hull.size() == 2) {
return 0.0;
}
double minWidth = Double.MAX_VALUE;
int n = hull.size();
// Method 1: Check orientations perpendicular to edges
for (int i = 0; i < n; i++) {
Point p1 = hull.get(i);
Point p2 = hull.get((i + 1) % n);
double dx = p2.x() - p1.x();
double dy = p2.y() - p1.y();
double edgeLen = Math.sqrt(dx * dx + dy * dy);
if (edgeLen == 0) continue;
// Perpendicular to edge direction (measurement direction)
double perpX = -dy / edgeLen;
double perpY = dx / edgeLen;
double minProj = Double.MAX_VALUE;
double maxProj = Double.MIN_VALUE;
for (Point p : hull) {
double proj = p.x() * perpX + p.y() * perpY;
minProj = Math.min(minProj, proj);
maxProj = Math.max(maxProj, proj);
}
minWidth = Math.min(minWidth, maxProj - minProj);
}
// Method 2: Check orientations defined by vertex pairs
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Point p1 = hull.get(i);
Point p2 = hull.get(j);
double dx = p2.x() - p1.x();
double dy = p2.y() - p1.y();
double len = Math.sqrt(dx * dx + dy * dy);
if (len == 0) continue;
// Direction perpendicular to the line p1-p2
double perpX = -dy / len;
double perpY = dx / len;
double minProj = Double.MAX_VALUE;
double maxProj = Double.MIN_VALUE;
for (Point p : hull) {
double proj = p.x() * perpX + p.y() * perpY;
minProj = Math.min(minProj, proj);
maxProj = Math.max(maxProj, proj);
}
minWidth = Math.min(minWidth, maxProj - minProj);
}
}
return minWidth;
}
/**
* Computes the minimum-area bounding rectangle of a convex polygon using rotating calipers.
*
* @param points List of points representing a convex polygon
* @return Rectangle containing the minimum-area bounding rectangle
* @throws IllegalArgumentException if points is null or has less than 2 points
*/
public static Rectangle computeMinimumAreaBoundingRectangle(Collection<Point> points) {
if (points == null || points.size() < 2) {
throw new IllegalArgumentException("Points list must contain at least 2 points");
}
List<Point> hull = ConvexHull.convexHullRecursive(new ArrayList<>(points));
if (hull.size() < 2) {
throw new IllegalArgumentException("Convex hull must contain at least 2 points");
}
hull = ensureCounterClockwiseOrder(hull);
if (hull.size() == 2) {
Point p1 = hull.get(0);
Point p2 = hull.get(1);
return new Rectangle(p1, p2, 0.0);
}
int n = hull.size();
double minArea = Double.MAX_VALUE;
Rectangle bestRectangle = null;
for (int i = 0; i < n; i++) {
Point p1 = hull.get(i);
Point p2 = hull.get((i + 1) % n);
int j = findAntipodalPoint(hull, i);
double edgeLength = distance(p1, p2);
double height = distanceToLine(p1, p2, hull.get(j));
double area = edgeLength * height;
if (area < minArea) {
minArea = area;
Point bottomLeft = computeRectangleCorner(p1, p2, hull.get(j), true);
Point topRight = computeRectangleCorner(p1, p2, hull.get(j), false);
bestRectangle = new Rectangle(bottomLeft, topRight, area);
}
}
return bestRectangle;
}
/**
* Finds the antipodal point for a given edge using rotating calipers.
*/
private static int findAntipodalPoint(List<Point> hull, int edgeStart) {
int n = hull.size();
int j = (edgeStart + 1) % n;
Point p1 = hull.get(edgeStart);
Point p2 = hull.get((edgeStart + 1) % n);
while (true) {
Point next = hull.get((j + 1) % n);
double dist1 = distanceToLine(p1, p2, hull.get(j));
double dist2 = distanceToLine(p1, p2, next);
if (dist2 > dist1) {
j = (j + 1) % n;
} else {
break;
}
}
return j;
}
/**
* Computes a corner of the bounding rectangle.
*/
private static Point computeRectangleCorner(Point p1, Point p2, Point antipodal, boolean isBottomLeft) {
int minX = Math.min(Math.min(p1.x(), p2.x()), antipodal.x());
int maxX = Math.max(Math.max(p1.x(), p2.x()), antipodal.x());
int minY = Math.min(Math.min(p1.y(), p2.y()), antipodal.y());
int maxY = Math.max(Math.max(p1.y(), p2.y()), antipodal.y());
if (isBottomLeft) {
return new Point(minX, minY);
} else {
return new Point(maxX, maxY);
}
}
/**
* Computes the Euclidean distance between two points.
*/
private static double distance(Point p1, Point p2) {
int dx = p2.x() - p1.x();
int dy = p2.y() - p1.y();
return Math.sqrt(dx * dx + dy * dy);
}
/**
* Computes the perpendicular distance from a point to a line defined by two points.
*/
private static double distanceToLine(Point lineStart, Point lineEnd, Point point) {
int dx = lineEnd.x() - lineStart.x();
int dy = lineEnd.y() - lineStart.y();
if (dx == 0 && dy == 0) {
return distance(lineStart, point);
}
int px = point.x() - lineStart.x();
int py = point.y() - lineStart.y();
double crossProduct = Math.abs(px * dy - py * dx);
double lineLength = Math.sqrt(dx * dx + dy * dy);
return crossProduct / lineLength;
}
/**
* Ensures the hull points are in counter-clockwise order for rotating calipers.
* The convex hull algorithm returns points sorted by natural order, but rotating calipers
* requires counter-clockwise ordering.
*/
private static List<Point> ensureCounterClockwiseOrder(List<Point> hull) {
if (hull.size() <= 2) {
return hull;
}
// Find bottommost point (lowest y, then leftmost x)
Point bottomMost = hull.get(0);
int bottomIndex = 0;
for (int i = 1; i < hull.size(); i++) {
Point current = hull.get(i);
// Check if current point is better than current best
boolean isBetter = current.y() < bottomMost.y() || (current.y() == bottomMost.y() && current.x() < bottomMost.x());
if (isBetter) {
bottomMost = current;
bottomIndex = i;
}
}
List<Point> orderedHull = new ArrayList<>();
for (int i = 0; i < hull.size(); i++) {
orderedHull.add(hull.get((bottomIndex + i) % hull.size()));
}
if (orderedHull.size() >= 3) {
Point p1 = orderedHull.get(0);
Point p2 = orderedHull.get(1);
Point p3 = orderedHull.get(2);
if (Point.orientation(p1, p2, p3) < 0) {
Collections.reverse(orderedHull);
Collections.rotate(orderedHull, 1);
}
}
return orderedHull;
}
}