|
| 1 | +from algorithm import sorted |
| 2 | +from math import arctan2 |
| 3 | +from sequtils import deduplicate, map |
| 4 | +import sugar |
| 5 | + |
| 6 | +type Point[T: SomeNumber] = tuple[x, y: T] |
| 7 | + |
| 8 | +proc tup_to_point[T](t: (T, T)): Point[T] = |
| 9 | + (x: t[0], y: t[1]) |
| 10 | + |
| 11 | +proc is_counter_clockwise(p1, p2, p3: Point): bool = |
| 12 | + (p3.y - p1.y) * (p2.x - p1.x) >= (p2.y - p1.y) * (p3.x - p1.x) |
| 13 | + |
| 14 | +proc polar_angle(reference, point: Point): float = |
| 15 | + arctan2(float(point.y - reference.y), float(point.x - reference.x)) |
| 16 | + |
| 17 | +proc flipped_point_cmp(pa, pb: Point): int = |
| 18 | + if (pa.y, pa.x) < (pb.y, pb.x): -1 |
| 19 | + elif pa == pb: 0 |
| 20 | + else: 1 |
| 21 | + |
| 22 | +proc graham_scan(gift: seq[Point]): seq[Point] = |
| 23 | + # TODO make sure input has length >= 3 |
| 24 | + let |
| 25 | + gift_without_duplicates = sorted(deduplicate(gift), flipped_point_cmp) |
| 26 | + start = gift_without_duplicates[0] |
| 27 | + candidates = sorted(gift_without_duplicates[1..^1], |
| 28 | + proc (pa, pb: Point): int = |
| 29 | + if polar_angle(start, pa) < polar_angle(start, pb): -1 |
| 30 | + else: 1) |
| 31 | + # TODO take the approach outlined in the text where we perform rotations on |
| 32 | + # the candidates, rather than add to a new sequence |
| 33 | + var hull = @[start, candidates[0], candidates[1]] |
| 34 | + for candidate in candidates: |
| 35 | + while not is_counter_clockwise(hull[^2], hull[^1], candidate): |
| 36 | + discard pop(hull) |
| 37 | + add(hull, candidate) |
| 38 | + hull |
| 39 | + |
| 40 | +when isMainModule: |
| 41 | + let |
| 42 | + test_gift = @[(-5, 2), (5, 7), (-6, -12), (-14, -14), (9, 9), |
| 43 | + (-1, -1), (-10, 11), (-6, 15), (-6, -8), (15, -9), |
| 44 | + (7, -7), (-2, -9), (6, -5), (0, 14), (2, 8)].map(t => tup_to_point(t)) |
| 45 | + hull = graham_scan(test_gift) |
| 46 | + echo "Initial gift:" |
| 47 | + echo test_gift |
| 48 | + echo "Final hull:" |
| 49 | + echo hull |
0 commit comments