-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGrahamAlgorithm.py
65 lines (51 loc) · 1.43 KB
/
GrahamAlgorithm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from math import atan2, sqrt
from pointPosition import position
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
lowest_point = None
def angle(point):
return atan2(point.y - lowest_point.y, point.x - lowest_point.x)
def distance(point):
return sqrt((point.x - lowest_point.x)**2 + (point.y - lowest_point.y)**2)
def find_lowest(points):
temp_low = points[0]
minimum = float("inf")
for p in points:
if p.y < minimum:
temp_low = p
minimum = p.y
elif p.y == minimum and p.x < temp_low.x:
temp_low = p
global lowest_point
lowest_point = temp_low
def graham(points):
points = sorted(points, key=lambda x: (angle(x), distance(x)))
stack = []
stack.append(points[0])
stack.append(points[1])
stack.append(points[2])
for i in range(3, len(points)):
while position(stack[-1], stack[-2], points[i]) == 2:
stack.pop()
stack.append(points[i])
return stack
if __name__ == "__main__":
points = []
p1 = Point(3, 8)
p2 = Point(1, 4)
p3 = Point(2, 5)
p4 = Point(7, 2)
p5 = Point(3, 2)
p6 = Point(5, 4)
points.append(p1)
points.append(p2)
points.append(p3)
points.append(p4)
points.append(p5)
points.append(p6)
find_lowest(points)
hull = graham(points)
for point in hull:
print("Point x: " + str(point.x) + ", y: " + str(point.y))