Skip to content

Commit d238093

Browse files
committed
is_counter_clockwise should return a number
1 parent ccdf22e commit d238093

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

contents/graham_scan/code/nim/graham.nim

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,12 @@ type Point[T: SomeNumber] = tuple[x, y: T]
88
proc 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

1518
proc 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

contents/graham_scan/graham_scan.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ We can find whether a rotation is counter-clockwise with trigonometric functions
2929
{% sample lang="cpp" %}
3030
[import:10-12, lang="cpp"](code/c++/graham_scan.cpp)
3131
{% sample lang="nim" %}
32-
[import:15-17, lang:"nim"](code/nim/graham.nim)
32+
[import:11-16, lang:"nim"](code/nim/graham.nim)
3333
{% endmethod %}
3434

3535
If the output of this function is 0, the points are collinear.
@@ -61,7 +61,7 @@ In the end, the code should look something like this:
6161
{% sample lang="cpp" %}
6262
[import:14-47, lang="cpp"](code/c++/graham_scan.cpp)
6363
{% sample lang="nim" %}
64-
[import:25-51, lang:"nim"](code/nim/graham.nim)
64+
[import:28-54, lang:"nim"](code/nim/graham.nim)
6565
{% endmethod %}
6666

6767
### Bibliography

0 commit comments

Comments
 (0)