Skip to content

Commit ccdf22e

Browse files
committed
Documentation
1 parent f78a970 commit ccdf22e

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

contents/graham_scan/code/nim/graham.nim

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,15 @@ proc tup_to_point[T](t: (T, T)): Point[T] =
99
(x: t[0], y: t[1])
1010

1111
proc is_counter_clockwise(p1, p2, p3: Point): bool =
12+
## Do the given points form a counter-clockwise turn?
1213
(p3.y - p1.y) * (p2.x - p1.x) < (p2.y - p1.y) * (p3.x - p1.x)
1314

1415
proc polar_angle(reference, point: Point): float =
16+
## Find the polar angle of a point relative to a reference point
1517
arctan2(float(point.y - reference.y), float(point.x - reference.x))
1618

1719
proc flipped_point_cmp(pa, pb: Point): int =
20+
## Compare points first by their y-coordinate, then x-coordinate.
1821
if (pa.y, pa.x) < (pb.y, pb.x): -1
1922
elif pa == pb: 0
2023
else: 1
@@ -23,21 +26,26 @@ proc graham_scan(gift: seq[Point]): seq[Point] =
2326
assert(gift.len >= 3)
2427
var points = sorted(deduplicate(gift), flipped_point_cmp)
2528
let pivot = points[0]
29+
# Mimic sorting a sliced sequence without copying
2630
sort(toOpenArray(points, 1, high(points)),
2731
proc (pa, pb: Point): int =
2832
if polar_angle(pivot, pa) < polar_angle(pivot, pb): -1
2933
else: 1)
3034
var
35+
# Hull pointer
3136
m = 1
37+
# Needed because the iteration variable from a slice is immutable
3238
en = toSeq(low(points) + 2..high(points))
3339
for i in mitems(en):
3440
while is_counter_clockwise(points[m - 1], points[m], points[i]):
3541
if m > 1:
3642
m -= 1
43+
# All points are collinear
3744
elif i == points.len:
3845
break
3946
else:
4047
i += 1
48+
# Counter-clockwise point found, update hull and swap
4149
m += 1
4250
swap(points[i], points[m])
4351
points[0..m]

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:14-15, lang:"nim"](code/nim/graham.nim)
32+
[import:15-17, 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, lang:"nim"](code/nim/graham.nim)
64+
[import:25-51, lang:"nim"](code/nim/graham.nim)
6565
{% endmethod %}
6666

6767
### Bibliography

0 commit comments

Comments
 (0)