@@ -8,9 +8,12 @@ type Point[T: SomeNumber] = tuple[x, y: T]
8
8
proc tup_to_point [T](t: (T, T)): Point [T] =
9
9
(x: t[0 ], y: t[1 ])
10
10
11
- proc is_counter_clockwise (p1, p2, p3: Point ): bool =
12
- # # Do the given points form a counter-clockwise turn?
13
- (p3.y - p1.y) * (p2.x - p1.x) < (p2.y - p1.y) * (p3.x - p1.x)
11
+ proc cross_product [T](p1, p2, p3: Point [T]): T =
12
+ # # Form the cross product of three points. If the result is
13
+ # # - zero, the points are collinear.
14
+ # # - positive, the points form a counter-clockwise "left" turn.
15
+ # # - negative, the points form a clockwise "right" turn.
16
+ (p3.y - p1.y) * (p2.x - p1.x) - (p2.y - p1.y) * (p3.x - p1.x)
14
17
15
18
proc polar_angle (reference, point: Point ): float =
16
19
# # Find the polar angle of a point relative to a reference point
@@ -37,7 +40,7 @@ proc graham_scan(gift: seq[Point]): seq[Point] =
37
40
# Needed because the iteration variable from a slice is immutable
38
41
en = toSeq (low (points) + 2 .. high (points))
39
42
for i in mitems (en):
40
- while is_counter_clockwise (points[m - 1 ], points[m], points[i]):
43
+ while cross_product (points[m - 1 ], points[m], points[i]) <= 0 :
41
44
if m > 1 :
42
45
m -= 1
43
46
# All points are collinear
0 commit comments