Skip to content

Commit d9bd84e

Browse files
authored
Create Convex_Hull.py
Convex Hull (Jarvis' algo)
1 parent c9fb36e commit d9bd84e

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed

algorithms/python/Convex_Hull.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
class Point:
2+
def __init__(self, x, y):
3+
self.x = x
4+
self.y = y
5+
6+
7+
def Left_index(points):
8+
9+
minn = 0
10+
for i in range(1, len(points)):
11+
if points[i].x < points[minn].x:
12+
minn = i
13+
elif points[i].x == points[minn].x:
14+
if points[i].y > points[minn].y:
15+
minn = i
16+
return minn
17+
18+
19+
def orient(p, q, r):
20+
21+
22+
val = (q.y - p.y) * (r.x - q.x) - \
23+
(q.x - p.x) * (r.y - q.y)
24+
25+
if val == 0:
26+
return 0
27+
elif val > 0:
28+
return 1
29+
else:
30+
return 2
31+
32+
33+
def convexHull(points, n):
34+
# There must be at least 3 points
35+
if n < 3:
36+
return
37+
38+
# Find the leftmost point
39+
l = Left_index(points)
40+
41+
hull = []
42+
43+
44+
p = l
45+
q = 0
46+
while (True):
47+
48+
# Add current point to result
49+
hull.append(p)
50+
q = (p + 1) % n
51+
52+
for i in range(n):
53+
54+
if (orient(points[p],
55+
points[i], points[q]) == 2):
56+
q = i
57+
58+
59+
p = q
60+
61+
62+
if (p == l):
63+
break
64+
65+
# Print Result
66+
yy=[]
67+
for each in hull:
68+
xx=[]
69+
pin1,pin2 =(points[each].x, points[each].y)
70+
xx.append(pin1)
71+
xx.append(pin2)
72+
yy.append(xx)
73+
print(yy,"before")
74+
list_final=sorted(yy, key=lambda k: [k[0], k[1]])
75+
print(list_final,":after")
76+
for i in range(len(list_final)):
77+
print("({},{})".format(list_final[i][0], list_final[i][1]))
78+
79+
points = []
80+
n = int(input())
81+
for _ in range(n):
82+
string=input()
83+
x = ''
84+
y = ''
85+
i = 1
86+
cond = True
87+
while cond:
88+
if string[i] == (","):
89+
cond = False
90+
i += 1
91+
else:
92+
x += string[i]
93+
i += 1
94+
95+
cond = True
96+
while cond:
97+
if string[i] == (")"):
98+
cond = False
99+
else:
100+
y += string[i]
101+
i += 1
102+
# print(y)
103+
X=int(x)
104+
Y=int(y)
105+
points.append(Point(X, Y))
106+
107+
convexHull(points, len(points))

0 commit comments

Comments
 (0)