Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Day 17 of Advent of Code 2020 Solution"""
- from collections import Counter
- from itertools import chain, product
- def get_adjacent(point):
- """Yield tuples with values+-1 for each value in input point"""
- for adj in product(*[[i + n for n in (-1, 0, 1)] for i in point]):
- yield adj
- class ConwayCube:
- static = {2, 3}
- activator = 3
- def __init__(self, start_position: list[str], dimension: int = 3):
- self.active_points: set[tuple[int, ...]] = set()
- self.dimension: int = dimension - 2
- for y, row in enumerate(start_position):
- for x, col in enumerate(row):
- if start_position[y][x] == "#":
- self.active_points.add(tuple([x, y] + [0] * self.dimension))
- def __iter__(self):
- return self
- def __next__(self):
- next_active = set()
- adjacent_points = []
- for p in self.active_points:
- p_adjacent = [adj for adj in get_adjacent(p) if adj != p]
- adjacent_points.append(p_adjacent)
- n_adjacent = 0
- for a in p_adjacent:
- if a in self.active_points:
- n_adjacent += 1
- if n_adjacent in self.static:
- next_active.add(p)
- adjacent_points = [*chain.from_iterable(adjacent_points)]
- adjacent_count = Counter(adjacent_points)
- for p in adjacent_count:
- if p in self.active_points:
- pass
- else:
- if adjacent_count[p] == self.activator:
- next_active.add(p)
- self.active_points = next_active
- @property
- def active(self) -> int:
- return len(self.active_points)
- def cycle_cubes(file_location, dimensions=3, n_cycles=6) -> int:
- with open(file_location, "r") as f:
- data = [line.strip() for line in f.readlines()]
- cc = ConwayCube(data, dimensions)
- for _ in range(n_cycles):
- next(cc)
- return cc.active
- def part_a(file_location):
- return cycle_cubes(file_location, dimensions=3, n_cycles=6)
- def part_b(file_location):
- return cycle_cubes(file_location, dimensions=4, n_cycles=6)
- if __name__ == "__main__":
- file_location = r"data\day17.txt"
- print(part_a(file_location))
- print(part_b(file_location))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement