2
2
import matplotlib .pyplot as plt
3
3
import random
4
4
5
-
6
5
Point = namedtuple ('Point' , 'x y' )
7
6
8
7
@@ -19,26 +18,34 @@ def add(self, point):
19
18
def _get_orientation (self , origin , p1 , p2 ):
20
19
'''
21
20
Returns the orientation of the Point p1 with regards to Point p2 using origin.
21
+ Negative if p1 is clockwise of p2.
22
22
:param p1:
23
23
:param p2:
24
24
:return: integer
25
25
'''
26
26
difference = (
27
- ((p2 .x - origin .x ) * (p1 .y - origin .y ))
28
- - ((p1 .x - origin .x ) * (p2 .y - origin .y ))
29
- )
27
+ ((p2 .x - origin .x ) * (p1 .y - origin .y ))
28
+ - ((p1 .x - origin .x ) * (p2 .y - origin .y ))
29
+ )
30
30
31
31
return difference
32
32
33
33
def compute_hull (self ):
34
34
'''
35
- Computes the convex hull and returns the points on the hull.
35
+ Computes the points that make up the convex hull.
36
36
:return:
37
37
'''
38
- points = sorted ( self ._points , key = lambda temp_point : temp_point . x )
38
+ points = self ._points
39
39
40
+ # get leftmost point
40
41
start = points [0 ]
41
- point = points [0 ]
42
+ min_x = start .x
43
+ for p in points [1 :]:
44
+ if p .x < min_x :
45
+ min_x = p .x
46
+ start = p
47
+
48
+ point = start
42
49
self ._hull_points .append (start )
43
50
44
51
far_point = None
@@ -72,10 +79,12 @@ def get_hull_points(self):
72
79
return self ._hull_points
73
80
74
81
def display (self ):
82
+ # all points
75
83
x = [p .x for p in self ._points ]
76
84
y = [p .y for p in self ._points ]
77
85
plt .plot (x , y , marker = 'D' , linestyle = 'None' )
78
86
87
+ # hull points
79
88
hx = [p .x for p in self ._hull_points ]
80
89
hy = [p .y for p in self ._hull_points ]
81
90
plt .plot (hx , hy )
@@ -86,23 +95,10 @@ def display(self):
86
95
87
96
def main ():
88
97
ch = ConvexHull ()
89
- # for _ in range(10):
90
- # ch.add(Point(random.randint(0, 100), random.randint(0, 100)))
91
-
92
- ch .add (Point (1 , 4 ))
93
- ch .add (Point (3 , 12 ))
94
- ch .add (Point (5 , 7 ))
95
- ch .add (Point (3 , 6 ))
96
- ch .add (Point (12 , 19 ))
97
- ch .add (Point (4 , 8 ))
98
- ch .add (Point (5 , 7 ))
99
- ch .add (Point (9 , 3 ))
100
- ch .add (Point (9 , 6 ))
101
- ch .add (Point (10 , 6 ))
102
- ch .add (Point (8 , 16 ))
103
- ch .add (Point (2 , 6 ))
104
-
105
- ch .compute_hull ()
98
+ for _ in range (50 ):
99
+ ch .add (Point (random .randint (0 , 100 ), random .randint (0 , 100 )))
100
+
101
+ print ("Points on hull:" , ch .get_hull_points ())
106
102
ch .display ()
107
103
108
104
0 commit comments