AoC 2020 D17: Conway Cubes

Python | Problem statement | Source code | Tags: Cellular automata

← Previous Back to AoC Index Next →

Literally like any other cellular automaton problem. The general template looks like this:

def evolve(active: set[Point], get_neighbors: Callable[[Point], list[Point]]) -> set[Point]:
new_active = set[Point]()
candidates = active.union(
neighbor for p in active for neighbor in get_neighbors(p)
)
for p in candidates:
active_neighbors = sum(
(neighbor in active) for neighbor in get_neighbors(p)
)
if p in active and should_stay_active(active_neighbors):
new_active.add(p)
elif p not in active and should_become_active(active_neighbors):
new_active.add(p)
return new_active
python

Part 1 has 3D points and part 2 has 4D points, but otherwise they're identical. The only difference is the neighbor function. The biggest struggle might be how to get the types right in Python 3.9.

Point = TypeVar("Point", bound=tuple[int, ...])


def solve(
points: set[Point],
n: int,
neighbors: Callable[[Point, bool], Generator[Point, Any, None]],
):
alive = set(points)
for _ in range(n):
new_alive = set[Point]()
for p in itertools.chain.from_iterable(neighbors(p, True) for p in alive):
alive_neighbors = sum(np in alive for np in neighbors(p, False))
if p in alive and alive_neighbors == 2 or alive_neighbors == 3:
new_alive.add(p)
alive = new_alive
print(len(alive))
python

← Previous Back to AoC Index Next →