Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 641dbc4

Browse filesBrowse files
committed
Graham Scan Algo Added
1 parent a3563f5 commit 641dbc4
Copy full SHA for 641dbc4

File tree

Expand file treeCollapse file tree

1 file changed

+61
-0
lines changed
Filter options
Expand file treeCollapse file tree

1 file changed

+61
-0
lines changed
+61Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from random import randint
2+
import matplotlib.pyplot as plt
3+
4+
5+
def orientation(m, n, o):
6+
val = ((n[1]-m[1])*(o[0]-n[0])) - ((o[1]-n[1])*(n[0]-m[0]))
7+
if val > 0:
8+
return 1
9+
elif val < 0:
10+
return -1
11+
else:
12+
return 0
13+
14+
def distance(m, n):
15+
return (n[0]-m[0])**2 + (n[1]-m[1])**2
16+
17+
def Sorting_with_bubble(coordinates, b):
18+
for coord_ith in range(len(coordinates)):
19+
for j in range(len(coordinates)-coord_ith-1):
20+
if (orientation(b, coordinates[j], coordinates[j+1]) > 0) or (orientation(b, coordinates[j], coordinates[j+1])==0 and (distance(b, coordinates[j]) > distance(b, coordinates[j+1]))):
21+
temp = coordinates[j+1]
22+
coordinates[j+1] = coordinates[j]
23+
coordinates[j] = temp
24+
25+
return coordinates
26+
27+
28+
def Convex_hull_through_graham(coordinates):
29+
b = min(coordinates, key= lambda coord: (coord[1], coord[0]))
30+
coord_ith = coordinates.index(b)
31+
coordinates[coord_ith]=coordinates[0]
32+
coordinates[0] = b
33+
coordinates = [b] + Sorting_with_bubble(coordinates[1:], b)
34+
size_triplet = [coordinates[0], coordinates[1], coordinates[2]]
35+
for coord_ith in range(3, len(coordinates)):
36+
while len(size_triplet)>=3 and orientation(size_triplet[-2], size_triplet[-1], coordinates[coord_ith]) >= 0:
37+
size_triplet.pop()
38+
size_triplet.append(coordinates[coord_ith])
39+
return size_triplet+[size_triplet[0]]
40+
41+
42+
def random_points(n=30):
43+
coordinates = [(randint(0, n), randint(0, n)) for _ in range(n)]
44+
print (coordinates)
45+
return coordinates
46+
47+
48+
if __name__ == "__main__":
49+
coordinates = random_points(120)
50+
51+
X = [coord[0] for coord in coordinates]
52+
Y = [coord[1] for coord in coordinates]
53+
plt.plot(X, Y, '.b')
54+
55+
boundary_poly = Convex_hull_through_graham(coordinates)
56+
57+
X = [coord[0] for coord in boundary_poly]
58+
Y = [coord[1] for coord in boundary_poly]
59+
plt.plot(X, Y, '-og')
60+
61+
plt.show()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.