Skip to content

Instantly share code, notes, and snippets.

@villares
Created October 22, 2018 22:01
Show Gist options
  • Save villares/c150c1dcc30e6bbb76e7a6a425223309 to your computer and use it in GitHub Desktop.
Save villares/c150c1dcc30e6bbb76e7a6a425223309 to your computer and use it in GitHub Desktop.
Assuming some tuples represent line segments of a closed polygon, order them
"""
Let's order some poly line segments!
A B C D E F G H I
0 1 2 3 4 5 6 7 8
A0 B1
+----+
| |
| |
D3+ +----+F5
| E4 |
| |
+----+----+
G6 H7 I8
"""
A, B, C, D, E, F, G, H, I, = range(9)
unord = [(E, B), (F, E), (F, I), (H, I), (A, D), (A, B), (D, G), (H, G),]
# first sort the segments
p0, p1 = unord.pop()
ord = [(p0, p1)]
while unord:
for pair in unord:
if p0 in pair or p1 in pair:
ord.append(pair)
unord.remove(pair)
p0, p1 = pair[0], pair[1]
break
else: # break a possible infinite while
print("malformed edge sequence")
break
# now fix each segment's internal vertex order
unord = ord
p0, p1 = unord.pop(0)
if p1 != unord[0][0]:
p1, p0 = p0, p1
ord = [(p0, p1)]
for pair in unord:
if p1 == pair[0]:
p0, p1 = pair[0], pair[1]
else:
p0, p1 = pair[1], pair[0]
ord.append((p0, p1))
print(ord)
@villares
Copy link
Author

# if you want the vertex points only :)
p0, p1 = ord.pop(0)
if p1 != ord[0][0]:
    p1, p0 = p0, p1
points = [p0]
for pair in ord:
    if p1 == pair[0]:
        p0, p1 = pair[0], pair[1]        
    else:
        p0, p1 = pair[1], pair[0]
    points.append(p0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment