Compare commits
2 commits
dd5f89d76d
...
78c8874102
Author | SHA1 | Date | |
---|---|---|---|
78c8874102 | |||
547552026b |
1 changed files with 59 additions and 0 deletions
59
gift_wrapping/wrap.py
Normal file
59
gift_wrapping/wrap.py
Normal file
|
@ -0,0 +1,59 @@
|
|||
# Gift wrapping algorithm
|
||||
# https://en.wikipedia.org/wiki/Gift_wrapping_algorithm
|
||||
# Date: 2021-11-16
|
||||
|
||||
import random
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def generate_points(n=100):
|
||||
X = []
|
||||
Y = []
|
||||
for _i in range(n):
|
||||
X.append(random.random())
|
||||
Y.append(random.random())
|
||||
plt.plot(X, Y, ".")
|
||||
return [(X[i], Y[i]) for i in range(n)]
|
||||
|
||||
|
||||
def cross_product(u, v):
|
||||
x1, y1 = u
|
||||
x2, y2 = v
|
||||
return x1 * y2 - x2 * y1
|
||||
|
||||
|
||||
def gift_wrapping(points):
|
||||
convex_hull = []
|
||||
x_sorted = sorted(points, key=lambda point: point[0])
|
||||
left_most = x_sorted[0]
|
||||
point_on_hull = left_most
|
||||
endpoint = None
|
||||
while endpoint != left_most:
|
||||
convex_hull.append(point_on_hull)
|
||||
endpoint = points[0]
|
||||
for point in points:
|
||||
cp = cross_product(
|
||||
(endpoint[0] - point_on_hull[0], endpoint[1] - point_on_hull[1]),
|
||||
(point[0] - point_on_hull[0], point[1] - point_on_hull[1]),
|
||||
)
|
||||
if endpoint == point_on_hull or cp < 0:
|
||||
endpoint = point
|
||||
point_on_hull = endpoint
|
||||
return convex_hull
|
||||
|
||||
|
||||
def draw_points(points, with_edge=False):
|
||||
X, Y = [], []
|
||||
for p in points:
|
||||
X.append(p[0])
|
||||
Y.append(p[1])
|
||||
plt.plot(X, Y, "." if not with_edge else "")
|
||||
|
||||
|
||||
pts = generate_points(50)
|
||||
|
||||
print(pts)
|
||||
draw_points(pts)
|
||||
hull = gift_wrapping(pts)
|
||||
draw_points(hull + [hull[0]], True)
|
||||
plt.show()
|
Loading…
Reference in a new issue