advent-of-code/2017-python/solutions/day_14.py

57 lines
1.5 KiB
Python
Raw Normal View History

2021-11-01 16:40:46 +01:00
from solutions import BaseSolution
from solutions.day_10 import Solution as KnotHash
class Solution(BaseSolution):
2025-05-06 20:14:58 +02:00
input_file = "14.txt"
2021-11-01 16:40:46 +01:00
def __str__(self):
2025-05-06 20:14:58 +02:00
return "Day 14: Disk Defragmentation"
2021-11-01 16:40:46 +01:00
def _get_grid(self, pi):
2025-05-06 20:14:58 +02:00
grid = ""
2021-11-01 16:40:46 +01:00
ks = KnotHash()
for n in range(128):
2025-05-06 20:14:58 +02:00
s = "-".join([pi, str(n)])
2021-11-01 16:40:46 +01:00
knothash = ks.solve_again(s)
2025-05-06 20:14:58 +02:00
grid += "{:0128b}".format(int(knothash, 16))
2021-11-01 16:40:46 +01:00
return grid
def _find_regions(self, squares):
seen = set()
regions = 0
def get_adjacent_square(i):
if i in seen or i not in squares:
return
seen.add(i)
if i % 128 > 0:
get_adjacent_square(i - 1)
if i > 127:
get_adjacent_square(i - 128)
if i % 128 < 127:
get_adjacent_square(i + 1)
2025-05-06 20:14:58 +02:00
if i < 128**2 - 128:
2021-11-01 16:40:46 +01:00
get_adjacent_square(i + 128)
2025-05-06 20:14:58 +02:00
for i in range(128**2):
2021-11-01 16:40:46 +01:00
if i in seen or i not in squares:
continue
regions += 1
get_adjacent_square(i)
return regions
def solve(self, puzzle_input):
grid = self._get_grid(puzzle_input)
return sum(map(int, grid))
def solve_again(self, puzzle_input):
grid = self._get_grid(puzzle_input)
2025-05-06 20:14:58 +02:00
squares = [i for i, s in enumerate(list(grid)) if s == "1"]
2021-11-01 16:40:46 +01:00
return self._find_regions(squares)
2025-05-06 20:14:58 +02:00
if __name__ == "__main__":
2021-11-01 16:40:46 +01:00
solution = Solution()
solution.show_results()