Skip to content

Instantly share code, notes, and snippets.

@marcojetson
Created September 19, 2018 08:13
Show Gist options
  • Save marcojetson/303e3b9212bc51342806eb2d4500ca31 to your computer and use it in GitHub Desktop.
Save marcojetson/303e3b9212bc51342806eb2d4500ca31 to your computer and use it in GitHub Desktop.
Compress a route by removing collinear points
def compress_route(route):
compressed = []
for point in route:
compressed.append(point)
if len(compressed) >= 3 and is_collinear(*compressed[-3:]):
del compressed[-2]
return compressed
def is_collinear(a, b, c):
return abs((a[0]*(b[1]-c[1])+b[0]*(c[1]-a[1])+c[0]*(a[1]-b[1]))/2) == 0
assert is_collinear([0, 5], [5, 5], [10, 5])
assert not is_collinear([0, 5], [5, 10], [10, 5])
assert [[0, 1], [2, 1], [2, 4], [5, 7], [9, 7]] == compress_route([
[0, 1],
[1, 1],
[2, 1],
[2, 2],
[2, 3],
[2, 4],
[3, 5],
[4, 6],
[5, 7],
[7, 7],
[8, 7],
[9, 7],
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment