Solve 2018 day 18

This commit is contained in:
felixm 2024-07-21 16:16:14 -04:00
parent b88326a7d1
commit 9f616a5b81
3 changed files with 73 additions and 1 deletions

68
2018/d18.py Normal file
View File

@ -0,0 +1,68 @@
from lib import get_data, Grid2D
from copy import deepcopy
def part_2(data, target=10):
g = Grid2D(data)
seen = {}
i = 0
while i < target:
ng = deepcopy(g)
for r in range(g.n_rows):
for c in range(g.n_cols):
if g[(r, c)] == ".":
tree_count = sum(
[1 if g[nb] == "|" else 0 for nb in g.neighbors_adj((r, c))]
)
if tree_count >= 3:
ng[(r, c)] = "|"
elif g[(r, c)] == "|":
lumber_count = sum(
[1 if g[nb] == "#" else 0 for nb in g.neighbors_adj((r, c))]
)
if lumber_count >= 3:
ng[(r, c)] = "#"
elif g[(r, c)] == "#":
tree_count = sum(
[1 if g[nb] == "|" else 0 for nb in g.neighbors_adj((r, c))]
)
lumber_count = sum(
[1 if g[nb] == "#" else 0 for nb in g.neighbors_adj((r, c))]
)
if tree_count > 0 and lumber_count > 0:
pass
else:
ng[(r, c)] = "."
else:
assert False
h = ng.hash()
if h in seen:
delta = i - seen[h]
while (i + delta) < target:
i += delta
seen = {}
else:
seen[h] = i
i += 1
g = ng
w = 0
l = 0
for r in range(g.n_rows):
for c in range(g.n_cols):
if g[(r, c)] == "|":
w += 1
elif g[(r, c)] == "#":
l += 1
print(l * w)
def main():
data = get_data(__file__)
part_2(data, 10)
part_2(data, 1000000000)
if __name__ == "__main__":
main()

View File

@ -106,7 +106,8 @@ written in Python.
- Day 15: 185:11 - Day 15: 185:11
- Day 16: 36:10 - Day 16: 36:10
- Day 17: 180:00 - Day 17: 180:00
- Day 18: - Day 18: 24:04
- Day 19:
# 2022 # 2022

3
lib.py
View File

@ -56,6 +56,9 @@ class Grid2D:
row, col = pos row, col = pos
self.grid[row][col] = val self.grid[row][col] = val
def hash(self):
return tuple(map(lambda row: tuple(row), self.grid))
def clone_with_val(self, val): def clone_with_val(self, val):
c = Grid2D("d\nd") c = Grid2D("d\nd")
c.n_rows = self.n_rows c.n_rows = self.n_rows