Compare commits
No commits in common. "78c8874102e1d020f569363bd064c67c81bf1b2d" and "dd5f89d76da649dfab1e27bc19ceb6e134bececd" have entirely different histories.
78c8874102
...
dd5f89d76d
1 changed files with 0 additions and 59 deletions
|
@ -1,59 +0,0 @@
|
||||||
# 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