import functools
def ccw(a, b, c):
"""
Calculate the cross product to determine the orientation.
Returns:
>0 if a->b->c is counter-clockwise,
<0 if clockwise,
0 if colinear.
"""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def distance_sq(a, b):
"""
Calculate the squared Euclidean distance between two points.
"""
dx = a[0] - b[0]
dy = a[1] - b[1]
return dx * dx + dy * dy
def polar_order(pivot):
"""
Create a comparison function that sorts points based on the polar angle
they make with the pivot point.
"""
def order(a, b):
orient = ccw(pivot, a, b)
if orient == 0:
# Points a and b are colinear with pivot
# Sort by distance to pivot
dist_a = distance_sq(pivot, a)
dist_b = distance_sq(pivot, b)
return dist_a - dist_b
else:
return -orient # Negative for sorting in counter-clockwise order
return order
def convex_hull(points):
"""
Compute the convex hull of a set of 2D points using Graham's scan algorithm.
Args:
points: List of (x, y) tuples representing the points.
Returns:
List of points forming the convex hull in counter-clockwise order.
"""
if len(points) <= 1:
return points[:]
# Step 1: Find the point with the smallest y-coordinate (pivot)
# Break ties by smallest x-coordinate
pivot = min(points, key=lambda p: (p[1], p[0]))
points.remove(pivot)
# Step 2: Sort the remaining points based on the polar angle with the pivot
points.sort(key=functools.cmp_to_key(polar_order(pivot)))
# Step 3: Build the convex hull using a stack
hull = [pivot, points[0]]
for point in points[1:]:
while len(hull) >= 2 and ccw(hull[-2], hull[-1], point) <= 0:
# Pop the last point from the hull if we make a non-left turn
hull.pop()
hull.append(point)
return hull
# Example usage:
# Define a set of points
points = [
(0, 0), (1, 1), (2, 0), (2, 2),
(1, 2), (0, 2), (1, 0.5), (1.5, 1.5)
]
# Compute the convex hull
hull = convex_hull(points)
print("Convex Hull:")
for point in hull:
print(point)
This code implements the Graham scan algorithm to compute the convex hull of a set of 2D points.
Explanation:
-
CCW Function:
The ccw function computes the cross product of vectors (a→b) and (a→c). The sign of the cross product determines the orientation:
- Positive (>0): Counter-clockwise turn.
- Negative (<0): Clockwise turn.
- Zero (0): Colinear points.
-
Sorting Points by Polar Angle:
The polar_order function creates a comparator that sorts points based on the polar angle they make with the pivot point. If two points have the same angle (they are colinear with the pivot), we sort them by their distance to the pivot to ensure the closest one comes first.
-
Building the Convex Hull:
We iterate through the sorted points and use a stack (hull) to build the convex hull:
- If the last two points in the hull and the current point make a non-left turn (i.e.,
ccw ≤ 0), we pop the last point from the hull.
- We then append the current point to the hull.
Result:
Running the code with the provided points will output the convex hull points in counter-clockwise order.
Sample Output:
Convex Hull:
(0, 0)
(2, 0)
(2, 2)
(0, 2)
These points form the convex polygon that encloses all the given points.
Note: This implementation avoids calculating explicit angles using trigonometric functions, which improves performance and numerical stability, especially with a large number of points.