adventofcode2022/day14/sol.py

121 lines
2.1 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))
xs.append(x)
ys.append(y)
data.append(path)
grid = []
sand = {}
X0 = min(xs)
X1 = max(xs) + 1
Y0 = 0
Y1 = max(ys) + 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):
if c == 'o':
sand[(x,y)] = c
if X0 <= x < X1:
if Y0 <= y < Y1:
grid[y-Y0][x-X0] = c
return
print(x,y,"out of range")
def get(x,y):
if (x,y) in sand:
return 'o'
if X0 <= x < X1:
if Y0 <= y < Y1:
return grid[y-Y0][x-X0]
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 r in grid: print("".join(r))
#show()
def drip(p):
x,y=p
while True:
c = get(x,y+1)
if c == '?':
return 'bye'
if c == '.':
y += 1
continue
# try left
c = get(x-1,y+1)
if c == '?':
return 'bye'
if c == '.':
x,y = x-1,y+1
continue
# try right
c = get(x+1, y+1)
if c == '?':
return 'bye'
if c == '.':
x,y = x+1, y+1
continue
# blocked!
put(x,y,'o')
#print(x,y)
return 'done'
#i = 0
#for _ in range(100000):
# if drip(source) == 'bye':
# break
# i+= 1
i = 0
while source not in sand:
drip(source)
i += 1
#show()
print(i)