day 14 python more cleanup

main
magical 2022-12-14 00:59:58 -08:00
parent 80cf54d600
commit 37e5ab92e0
1 changed files with 46 additions and 62 deletions

View File

@ -2,8 +2,6 @@
source = (500,0) source = (500,0)
data = [] data = []
xs = []
ys = []
for line in open("input"): for line in open("input"):
path = [] path = []
for point in line.replace("->", " ").split(): for point in line.replace("->", " ").split():
@ -21,38 +19,29 @@ Y1 = 1
def put(x,y,c): def put(x,y,c):
global X0, X1, Y0, Y1 global X0, X1, Y0, Y1
if x < X0: if x < X0: X0 = x
X0 = x if x >= X1: X1 = x + 1
if x >= X1: if y < Y0: Y0 = y
X1 = x + 1 if y >= Y1: Y1 = y + 1
if y < Y0:
Y0 = y
if y >= Y1:
Y1 = y + 1
grid[(x,y)] = c grid[(x,y)] = c
def get(x,y): def get(x,y):
if (x,y) in grid: return grid.get((x,y), '.')
return grid[(x,y)]
return '.' def minmax(a,b):
if a < b:
return a, b
return b, a
def draw(path): def draw(path):
for p1, p2 in zip(path, path[1:]): for (x0,y0), (x1,y1) in zip(path, path[1:]):
#print(p1, p2) #print((x0,y0), (x1,y1))
if p1[0] == p2[0]: x0, x1 = minmax(x0, x1)
x = p1[0] y0, y1 = minmax(y0, y1)
y0, y1 = p1[1], p2[1]
if y0 > y1:
y0, y1 = y1, y0
for y in range(y0, y1+1): for y in range(y0, y1+1):
put(x,y, '#') put(x0,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): for x in range(x0, x1+1):
put(x,y, '#') put(x,y0, '#')
for path in data: for path in data:
#print(path) #print(path)
@ -69,53 +58,48 @@ def drip(p, floor=None, lastpath=[]):
x,y=p x,y=p
if p in lastpath: if p in lastpath:
x,y = lastpath.pop() x,y = lastpath.pop()
while True: else:
lastpath[:] = []
blocked = False
while not blocked:
lastpath.append((x,y)) lastpath.append((x,y))
if y+1 == floor: if y+1 == floor:
# blocked break
lastpath.pop()
put(x,y,'o')
return 'done'
if y >= Y1: if y >= Y1:
return 'bye' return 'bye' # falls forever
c = get(x,y+1) # try straight down, then left, then right
if c == '.': for x1 in x, x-1, x+1:
y += 1 if get(x1,y+1) == '.':
continue x,y = x1,y+1
# try left break # continue
c = get(x-1,y+1) else:
if c == '.': blocked = True
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! # blocked!
lastpath.pop() lastpath.pop()
put(x,y,'o') put(x,y,'o')
#print(x,y) #print(x,y)
return 'done' return 'done'
i = 0 n = 0
while True: while True:
if drip(source) == 'bye': if drip(source) == 'bye':
break break
i+= 1 n+= 1
print(i) print(n)
floor = Y1 + 1 floor = Y1 + 1
Y1 = floor+1 Y1 = floor+1
show() show()
# keep going
while source not in grid: while source not in grid:
r = drip(source, floor=floor) if drip(source, floor=floor) == 'bye':
i += 1 print("whoops") # shouldn't happen
if r == 'bye':
break break
n += 1
# 28594 # 28594
show() #show()
print(i) print(n)