adventofcode2022/day14/sol.py

117 lines
2.0 KiB
Python
Raw Normal View History

2022-12-14 05:45:47 +00:00
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)
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
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
2022-12-14 05:45:47 +00:00
def get(x,y):
2022-12-14 06:13:50 +00:00
if (x,y) in grid:
return grid[(x,y)]
return '.'
2022-12-14 05:45:47 +00:00
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():
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:13:50 +00:00
def drip(p, floor=None):
2022-12-14 05:45:47 +00:00
x,y=p
while True:
2022-12-14 06:13:50 +00:00
if y+1 == floor:
# blocked
put(x,y,'o')
return 'done'
if y >= Y1:
2022-12-14 05:45:47 +00:00
return 'bye'
2022-12-14 06:13:50 +00:00
c = get(x,y+1)
2022-12-14 05:45:47 +00:00
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
2022-12-14 06:13:50 +00:00
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)
2022-12-14 05:45:47 +00:00
i += 1
2022-12-14 06:13:50 +00:00
if r == 'bye':
break
# 28594
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
print(i)