aoc/22/day14.py
2023-12-04 10:25:33 +01:00

89 lines
2 KiB
Python
Executable file

#!/bin/python3
from collections import defaultdict
from enum import Enum
from itertools import pairwise
class Tile(Enum):
AIR = 1
ROCK = 2
SOURCE = 3
SAND = 4
grid = defaultdict(lambda: Tile.AIR)
with open('inputs/day14.txt', 'r') as f:
for line in f:
for (start, end) in pairwise(line.strip().split(' -> ')):
[sx, sy] = map(int, start.split(','))
[ex, ey] = map(int, end.split(','))
dx = 0
dy = 0
if ex > sx:
dx = 1
elif ex < sx:
dx = -1
if ey > sy:
dy = 1
elif ey < sy:
dy = -1
curx = sx
cury = sy
grid[(curx, cury)] = Tile.ROCK
while curx != ex or cury != ey:
curx += dx
cury += dy
grid[(curx, cury)] = Tile.ROCK
highest_y = -1
for (x, y), tile in grid.items():
if y > highest_y:
highest_y = y
def query_grid(x, y):
if y == highest_y + 2:
return Tile.ROCK
return grid[(x, y)]
(sourcex, sourcey) = (500, 0)
def abyss_underneath(x, y):
for (gridx, gridy), tile in grid.items():
if gridy > y and gridx == x and tile != Tile.AIR:
return False
return True
# voided = False
blocked = False
while True:
(x, y) = (sourcex, sourcey)
while True:
# if abyss_underneath(x, y):
# voided = True
# break
if query_grid(x, y+1) == Tile.AIR:
y += 1
elif query_grid(x-1, y+1) == Tile.AIR:
y += 1
x -= 1
elif query_grid(x+1, y+1) == Tile.AIR:
y += 1
x += 1
else:
if (x, y) == (sourcex, sourcey):
blocked = True
break
# if voided:
# break
if blocked:
break
grid[(x, y)] = Tile.SAND
rest_count = 0
for (x, y), tile in grid.items():
if tile == Tile.SAND:
rest_count += 1
print(rest_count + 1)