Part 1 | Part 2 | Total | |
---|---|---|---|
Time | 14:56 | 2:06 | 17:02 |
That's more like it! Rank 295 for Part 1, 205 for Part 2. This is the first time I've placed well in both parts. This one was refreshing after a couple of slow days for me.
The above visualization is for Part 2.
This was a puzzle where you just have to do it. I decided to store the rock walls in a defaultdict
and do nested while loops for the falling sand. When the sand stopped moving, I just treated it like a rock. All I had to do was break out of the outer loop when a peice of sand falls below the lowest point added during the rock wall creation stage.
from helpers.datagetter import data_in, submit
from collections import defaultdict
ans = -1
din = data_in(split=True, numbers=False)
rock = defaultdict(int)
lowest = 0
for line in din:
pts = line.split(" -> ")
for i in range(len(pts)-1):
first = eval("[" + pts[i] + "]")
second = eval("[" + pts[i+1] + "]")
if first[0] == second[0]:
for j in range(min(first[1], second[1]), max(first[1], second[1])+1):
rock[f"{first[0]},{j}"] = 1
lowest = max(lowest, j)
elif first[1] == second[1]:
for j in range(min(first[0], second[0]), max(first[0], second[0])+1):
rock[f"{j},{first[1]}"] = 1
lowest = max(lowest, first[1])
print(len(rock.values()))
found = False
while not found:
sx = 500
sy = 0
while True:
if sy >= lowest:
found = True
break
if rock[f"{sx},{sy+1}"] == 0:
sy += 1
else:
if rock[f"{sx-1},{sy+1}"] == 0:
sy += 1
sx -= 1
elif rock[f"{sx+1},{sy+1}"] == 0:
sy += 1
sx += 1
else:
rock[f"{sx},{sy}"] = 1
break
ans += 1
print(ans)
submit(ans)
For this part, it was as simple as adding a condition to place the sand when it checks at lowest + 1
since there is now a floor at lowest + 2
. And the new break out condition for the outer loop is as soon as a unit of sand is placed at (500, 0)
.
# REPLACE NESTED WHILE LOOPS WITH THIS
while True:
sx = 500
sy = 0
while True:
if sy >= lowest + 1:
rock[f"{sx},{sy}"] = 1
break
if rock[f"{sx},{sy+1}"] == 0:
sy += 1
else:
if rock[f"{sx-1},{sy+1}"] == 0:
sy += 1
sx -= 1
elif rock[f"{sx+1},{sy+1}"] == 0:
sy += 1
sx += 1
else:
rock[f"{sx},{sy}"] = 1
break
if sx == 500 and sy == 0:
break
ans += 1
ans += 2 # Because of where I placed the increment of ans
print(ans)
submit(ans)