adventofcode2022/day15/clip.py

36 lines
979 B
Python

import pyclipper # https://pypi.org/project/pyclipper/
data = []
for line in open("input"):
words = line.replace(":", "").replace(",","").split()
coords = [int(w[w.index('=')+1:]) for w in words if '=' in w]
data.append(coords)
pc = pyclipper.Pyclipper()
for sx,sy,bx,by in data:
dx = abs(sx-bx)
dy = abs(sy-by)
d = dx+dy
pc.AddPath([(sx+d,sy),(sx,sy+d),(sx-d,sy),(sx,sy-d)], pyclipper.PT_CLIP, closed=True)
M = 4000000
pc.AddPath([(0,0),(M,0),(M,M),(0,M)], pyclipper.PT_SUBJECT, closed=True)
solution = pc.Execute(pyclipper.CT_DIFFERENCE, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO)
# should return a single small polygon shaped like a diamond
# the answer we want is the point at the center of the diamond
assert len(solution) == 1
assert pyclipper.Area(solution[0]) < 4
def avg(ns):
return sum(ns)/len(ns)
for p in solution:
x = avg([x for x,y in p])
y = avg([y for x,y in p])
print(x,y)
print("frequency =",M*x + y)