@@ -27,12 +27,12 @@ impl Ord for Point {
27
27
}
28
28
29
29
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 )
31
31
}
32
32
33
33
// Calculate the polar angle of a point relative to a reference point.
34
34
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 )
36
36
}
37
37
38
38
fn graham_scan ( mut points : Vec < Point > ) -> Vec < Point > {
@@ -41,23 +41,22 @@ fn graham_scan(mut points: Vec<Point>) -> Vec<Point> {
41
41
let pivot = points. remove ( 0 ) ;
42
42
43
43
// 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 ) )
46
46
) . unwrap ( )
47
47
) ;
48
48
49
- // Reinsert the pivot point
50
49
points. insert ( 0 , pivot) ;
51
50
52
- let n = points. len ( ) ;
53
51
let mut m = 1 ;
54
52
55
53
// 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 {
58
56
if m > 1 {
59
57
m -= 1 ;
60
- } else if m == i {
58
+ // All points are colinear
59
+ } else if i == points. len ( ) {
61
60
break ;
62
61
} else {
63
62
i += 1 ;
0 commit comments