2023/day14.py

74 lines
1.6 KiB
Python
Raw Normal View History

2023-12-28 20:01:52 +00:00
import sys
from pprint import pprint
from copy import deepcopy
2024-01-04 03:43:34 +00:00
2023-12-28 20:01:52 +00:00
def shift(map, dx, dy):
2024-01-04 03:43:34 +00:00
for y in range(max(0, -dy), len(map) - max(0, dy)):
for x in range(max(0, -dx), len(map) - max(0, dx)):
(x1, y1) = (x, y)
while True:
(x2, y2) = (x1 + dx, y1 + dy)
if 0 <= y2 < len(map) and 0 <= x2 < len(map[y2]) and map[y2][x2] == ".":
(x1, y1) = (x2, y2)
else:
break
if (x1, y1) != (x, y):
map[y1][x1] = "O"
map[y][x] = "."
2023-12-28 20:01:52 +00:00
def weigh(map):
return sum((len(map) - y) * row.count("O") for (y, row) in enumerate(map))
2024-01-04 03:43:34 +00:00
# @profile
2023-12-28 20:01:52 +00:00
def main():
2024-01-04 03:43:34 +00:00
CYCLES = 1_000_000_000
2023-12-28 20:01:52 +00:00
with open(sys.argv[1]) as f:
2024-01-04 03:43:34 +00:00
map = [[c for c in l] for l in f.read().strip().splitlines()]
2023-12-28 20:01:52 +00:00
part1 = 0
2024-01-04 03:43:34 +00:00
pprint(map)
2023-12-28 20:01:52 +00:00
shift(map, 0, -1)
2024-01-04 03:43:34 +00:00
pprint(map)
2023-12-28 20:01:52 +00:00
part1 = weigh(map)
2024-01-04 03:43:34 +00:00
shift(map, -1, 0)
pprint(map)
shift(map, 0, 1)
pprint(map)
shift(map, 1, 0)
pprint(map)
for i in range(1, 100):
shift(map, 0, -1)
shift(map, -1, 0)
shift(map, 0, 1)
shift(map, 1, 0)
2023-12-28 20:01:52 +00:00
seen = {}
history = []
2024-01-04 03:43:34 +00:00
(i, j) = (0, 0)
for i in range(100, CYCLES):
2023-12-28 20:01:52 +00:00
shift(map, 0, -1)
shift(map, -1, 0)
shift(map, 0, 1)
shift(map, 1, 0)
s = str(map)
2024-01-04 03:43:34 +00:00
history.append(weigh(map))
2023-12-28 20:01:52 +00:00
if s in seen:
2024-01-04 03:43:34 +00:00
j = seen[s]
2023-12-28 20:01:52 +00:00
break
seen[s] = i
2024-01-04 03:43:34 +00:00
offset = (CYCLES - j) % (i - j) - 1
2023-12-28 20:01:52 +00:00
part2 = history[offset]
print(part1, part2)
main()