Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pathlib import Path
- import re
- from collections import Counter
- TEST = """**REDACTED**"""
- def parse(input: str) -> list[tuple[int, int, int, int]]:
- robots: list[tuple[int, int, int, int]] = []
- for row in input.splitlines():
- pos = [int(n) for n in re.findall("-?\\d+", row)]
- assert len(pos) == 4
- robots.append(tuple(pos))
- return robots
- def part1(input: str, width: int = 101, height: int = 103, moves: int = 100) -> int:
- quadrants: list[int] = [0, 0, 0, 0]
- w2, h2 = width // 2, height // 2
- for robot in parse(input):
- px, py, vx, vy = robot
- fx = (px + moves * vx) % width
- fy = (py + moves * vy) % height
- if fx != w2 and fy != h2:
- quadrants[(1 if fx > w2 else 0) + (2 if fy > h2 else 0)] += 1
- return quadrants[0] * quadrants[1] * quadrants[2] * quadrants[3]
- assert part1(TEST, 11, 7) == 12
- INPUT = Path("input/day14.txt").read_text()
- part1_total = part1(INPUT)
- print(f"{part1_total=:,}") # 230,900,224
- def treeness(
- move: int,
- robots: list[tuple[int, int, int, int]],
- width: int,
- height: int,
- branches=6,
- ) -> int:
- # Tree picture will have a lot of robots with close neighbours
- points = {
- complex((px + move * vx) % width, (py + move * vy) % height)
- for px, py, vx, vy in robots
- }
- neighbours = sum(
- len(
- {
- p + 1,
- p - 1,
- p + 1j,
- p - 1j,
- p + 1 + 1j,
- p + 1 - 1j,
- p - 1 + 1j,
- p - 1 - 1j,
- }
- & points
- )
- for p in points
- )
- return neighbours
- def show(
- move: int, robots: list[tuple[int, int, int, int]], width: int, height: int
- ) -> None:
- grid = [[" "] * width for i in range(height)]
- for px, py, vx, vy in robots:
- fx = (px + move * vx) % width
- fy = (py + move * vy) % height
- grid[fy][fx] = "*"
- for row in grid:
- print("".join(row))
- def part2(inp: str, width: int = 101, height: int = 103, moves: int = 100) -> int:
- w2, h2 = width // 2, height // 2
- robots = parse(inp)
- moves: Counter[int] = Counter()
- for move in range(1, width * height):
- moves[move] = treeness(move, robots, width, height)
- for move, score in moves.most_common(1):
- print(move, score)
- show(move, robots, width, height)
- return moves.most_common(1)[0][0]
- print(f"{part2(INPUT)=:,}") # 6532
Advertisement
Add Comment
Please, Sign In to add comment