@@ -8,9 +8,12 @@ type Point[T: SomeNumber] = tuple[x, y: T]
88proc tup_to_point [T](t: (T, T)): Point [T] =
99 (x: t[0 ], y: t[1 ])
1010
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)
1417
1518proc polar_angle (reference, point: Point ): float =
1619 # # Find the polar angle of a point relative to a reference point
@@ -37,7 +40,7 @@ proc graham_scan(gift: seq[Point]): seq[Point] =
3740 # Needed because the iteration variable from a slice is immutable
3841 en = toSeq (low (points) + 2 .. high (points))
3942 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 :
4144 if m > 1 :
4245 m -= 1
4346 # All points are collinear
0 commit comments