Skip to content

Commit cb13797

Browse files
Apply requested changes from algorithm-archivists#479
1 parent e823152 commit cb13797

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

contents/graham_scan/code/rust/graham_scan.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,12 @@ impl Ord for Point {
2727
}
2828

2929
fn counter_clockwise(a: &Point, b: &Point, c: &Point) -> bool {
30-
(b.x - a.x) * (c.y - a.y) >= (b.y - a.y) * (c.x - a.x)
30+
(b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
3131
}
3232

3333
// Calculate the polar angle of a point relative to a reference point.
3434
fn polar_angle(reference: &Point, point: &Point) -> f64 {
35-
(point.y - point.y).atan2(point.x - reference.x)
35+
(point.y - reference.y).atan2(point.x - reference.x)
3636
}
3737

3838
fn graham_scan(mut points: Vec<Point>) -> Vec<Point> {
@@ -41,23 +41,22 @@ fn graham_scan(mut points: Vec<Point>) -> Vec<Point> {
4141
let pivot = points.remove(0);
4242

4343
// Sort all points based on the angle between the pivot point and itself
44-
&mut points.sort_by(|a, b| (polar_angle(a, &pivot).
45-
partial_cmp(&polar_angle(b, &pivot))
44+
&mut points.sort_by(|a, b| (polar_angle(&pivot, a).
45+
partial_cmp(&polar_angle(&pivot, b))
4646
).unwrap()
4747
);
4848

49-
// Reinsert the pivot point
5049
points.insert(0, pivot);
5150

52-
let n = points.len();
5351
let mut m = 1;
5452

5553
// Move the points of the hull towards the beginning of the vector.
56-
for mut i in 2..n {
57-
while counter_clockwise(&points[m - 1], &points[m], &points[i]) {
54+
for mut i in 2..points.len() {
55+
while counter_clockwise(&points[m - 1], &points[m], &points[i]) <= 0 {
5856
if m > 1 {
5957
m -= 1;
60-
} else if m == i {
58+
// All points are colinear
59+
} else if i == points.len() {
6160
break;
6261
} else {
6362
i += 1;

0 commit comments

Comments
 (0)