adventofcode2022/day14/sol.py

106 lines
1.9 KiB
Python
Raw Normal View History

2022-12-14 05:45:47 +00:00
source = (500,0)
data = []
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)
2022-12-14 06:13:50 +00:00
grid = {}
2022-12-14 05:45:47 +00:00
2022-12-14 06:13:50 +00:00
X0 = 500
X1 = 500 + 1
2022-12-14 05:45:47 +00:00
Y0 = 0
2022-12-14 06:13:50 +00:00
Y1 = 1
2022-12-14 05:45:47 +00:00
def put(x,y,c):
2022-12-14 06:13:50 +00:00
global X0, X1, Y0, Y1
2022-12-14 08:59:58 +00:00
if x < X0: X0 = x
if x >= X1: X1 = x + 1
if y < Y0: Y0 = y
if y >= Y1: Y1 = y + 1
2022-12-14 06:13:50 +00:00
grid[(x,y)] = c
2022-12-14 05:45:47 +00:00
def get(x,y):
2022-12-14 08:59:58 +00:00
return grid.get((x,y), '.')
def minmax(a,b):
if a < b:
return a, b
return b, a
2022-12-14 05:45:47 +00:00
def draw(path):
2022-12-14 08:59:58 +00:00
for (x0,y0), (x1,y1) in zip(path, path[1:]):
#print((x0,y0), (x1,y1))
x0, x1 = minmax(x0, x1)
y0, y1 = minmax(y0, y1)
for y in range(y0, y1+1):
put(x0,y, '#')
for x in range(x0, x1+1):
put(x,y0, '#')
2022-12-14 05:45:47 +00:00
for path in data:
#print(path)
draw(path)
def show():
2022-12-14 06:13:50 +00:00
for y in range(Y0, Y1):
print("".join(get(x,y) for x in range(X0, X1)))
2022-12-14 05:45:47 +00:00
2022-12-14 06:13:50 +00:00
show()
2022-12-14 05:45:47 +00:00
2022-12-14 06:18:59 +00:00
def drip(p, floor=None, lastpath=[]):
2022-12-14 05:45:47 +00:00
x,y=p
2022-12-14 06:18:59 +00:00
if p in lastpath:
x,y = lastpath.pop()
2022-12-14 08:59:58 +00:00
else:
lastpath[:] = []
blocked = False
while not blocked:
2022-12-14 06:18:59 +00:00
lastpath.append((x,y))
2022-12-14 06:13:50 +00:00
if y+1 == floor:
2022-12-14 08:59:58 +00:00
break
2022-12-14 06:13:50 +00:00
if y >= Y1:
2022-12-14 08:59:58 +00:00
return 'bye' # falls forever
# try straight down, then left, then right
for x1 in x, x-1, x+1:
if get(x1,y+1) == '.':
x,y = x1,y+1
break # continue
else:
blocked = True
# blocked!
lastpath.pop()
put(x,y,'o')
#print(x,y)
return 'done'
n = 0
2022-12-14 06:13:50 +00:00
while True:
if drip(source) == 'bye':
break
2022-12-14 08:59:58 +00:00
n+= 1
print(n)
2022-12-14 06:13:50 +00:00
floor = Y1 + 1
Y1 = floor+1
show()
2022-12-14 08:59:58 +00:00
# keep going
2022-12-14 06:13:50 +00:00
while source not in grid:
2022-12-14 08:59:58 +00:00
if drip(source, floor=floor) == 'bye':
print("whoops") # shouldn't happen
2022-12-14 06:13:50 +00:00
break
2022-12-14 08:59:58 +00:00
n += 1
2022-12-14 06:13:50 +00:00
# 28594
2022-12-14 05:45:47 +00:00
2022-12-14 08:59:58 +00:00
#show()
print(n)