adventofcode2022/day14/sol.py

117 lines
2.0 KiB
Python

source = (500,0)
data = []
xs = []
ys = []
for line in open("input"):
path = []
for point in line.replace("->", " ").split():
x, y = map(int, point.split(","))
path.append((x,y))
data.append(path)
grid = {}
X0 = 500
X1 = 500 + 1
Y0 = 0
Y1 = 1
def put(x,y,c):
global X0, X1, Y0, Y1
if x < X0:
X0 = x
if x >= X1:
X1 = x + 1
if y < Y0:
Y0 = y
if y >= Y1:
Y1 = y + 1
grid[(x,y)] = c
def get(x,y):
if (x,y) in grid:
return grid[(x,y)]
return '.'
def draw(path):
for p1, p2 in zip(path, path[1:]):
#print(p1, p2)
if p1[0] == p2[0]:
x = p1[0]
y0, y1 = p1[1], p2[1]
if y0 > y1:
y0, y1 = y1, y0
for y in range(y0, y1+1):
put(x,y, '#')
else:
y = p1[1]
x0, x1 = p1[0], p2[0]
if x0 > x1:
x0, x1 = x1, x0
for x in range(x0, x1+1):
put(x,y, '#')
for path in data:
#print(path)
draw(path)
def show():
for y in range(Y0, Y1):
print("".join(get(x,y) for x in range(X0, X1)))
show()
def drip(p, floor=None):
x,y=p
while True:
if y+1 == floor:
# blocked
put(x,y,'o')
return 'done'
if y >= Y1:
return 'bye'
c = get(x,y+1)
if c == '.':
y += 1
continue
# try left
c = get(x-1,y+1)
if c == '.':
x,y = x-1,y+1
continue
# try right
c = get(x+1, y+1)
if c == '.':
x,y = x+1, y+1
continue
# blocked!
put(x,y,'o')
#print(x,y)
return 'done'
i = 0
while True:
if drip(source) == 'bye':
break
i+= 1
print(i)
floor = Y1 + 1
Y1 = floor+1
show()
while source not in grid:
r = drip(source, floor=floor)
i += 1
if r == 'bye':
break
# 28594
show()
print(i)