day 14 python cleanup

main
magical 2022-12-13 22:13:50 -08:00
parent 96a5961ed4
commit 99fa431441
1 changed files with 46 additions and 50 deletions

View File

@ -9,45 +9,32 @@ for line in open("input"):
for point in line.replace("->", " ").split(): for point in line.replace("->", " ").split():
x, y = map(int, point.split(",")) x, y = map(int, point.split(","))
path.append((x,y)) path.append((x,y))
xs.append(x)
ys.append(y)
data.append(path) data.append(path)
grid = [] grid = {}
sand = {}
X0 = min(xs) X0 = 500
X1 = max(xs) + 1 X1 = 500 + 1
Y0 = 0 Y0 = 0
Y1 = max(ys) + 1 Y1 = 1
# part 2:
X0 -= 1000
X1 += 1000
Y1 += 1
DX = X1 - X0
DY = Y1 - Y0
grid = [['.']*DX for _ in range(DY)]
def put(x,y,c): def put(x,y,c):
if c == 'o': global X0, X1, Y0, Y1
sand[(x,y)] = c if x < X0:
if X0 <= x < X1: X0 = x
if Y0 <= y < Y1: if x >= X1:
grid[y-Y0][x-X0] = c X1 = x + 1
return if y < Y0:
print(x,y,"out of range") Y0 = y
if y >= Y1:
Y1 = y + 1
grid[(x,y)] = c
def get(x,y): def get(x,y):
if (x,y) in sand: if (x,y) in grid:
return 'o' return grid[(x,y)]
if X0 <= x < X1: return '.'
if Y0 <= y < Y1:
return grid[y-Y0][x-X0]
return '#'
def draw(path): def draw(path):
for p1, p2 in zip(path, path[1:]): for p1, p2 in zip(path, path[1:]):
@ -73,30 +60,31 @@ for path in data:
def show(): def show():
for r in grid: print("".join(r)) for y in range(Y0, Y1):
print("".join(get(x,y) for x in range(X0, X1)))
#show() show()
def drip(p): def drip(p, floor=None):
x,y=p x,y=p
while True: while True:
c = get(x,y+1) if y+1 == floor:
if c == '?': # blocked
put(x,y,'o')
return 'done'
if y >= Y1:
return 'bye' return 'bye'
c = get(x,y+1)
if c == '.': if c == '.':
y += 1 y += 1
continue continue
# try left # try left
c = get(x-1,y+1) c = get(x-1,y+1)
if c == '?':
return 'bye'
if c == '.': if c == '.':
x,y = x-1,y+1 x,y = x-1,y+1
continue continue
# try right # try right
c = get(x+1, y+1) c = get(x+1, y+1)
if c == '?':
return 'bye'
if c == '.': if c == '.':
x,y = x+1, y+1 x,y = x+1, y+1
continue continue
@ -105,16 +93,24 @@ def drip(p):
#print(x,y) #print(x,y)
return 'done' return 'done'
#i = 0
#for _ in range(100000):
# if drip(source) == 'bye':
# break
# i+= 1
i = 0 i = 0
while source not in sand: while True:
drip(source) if drip(source) == 'bye':
break
i+= 1 i+= 1
print(i)
#show()
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) print(i)