From 8e2da00dc503767be320c847d7bcf876baa89002 Mon Sep 17 00:00:00 2001 From: Holly McFarland Date: Wed, 11 Dec 2024 18:12:07 -0500 Subject: [PATCH] day 8 --- day_08/part_a.py | 38 ++++++++++++++++++++++++++++++++++ day_08/part_b.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 day_08/part_a.py create mode 100644 day_08/part_b.py diff --git a/day_08/part_a.py b/day_08/part_a.py new file mode 100644 index 0000000..aedf1a6 --- /dev/null +++ b/day_08/part_a.py @@ -0,0 +1,38 @@ +import aocd +import collections + +def solve(data): + grid = collections.defaultdict(list) + antinodes = set() + + rows = data.split('\n') + width = len(rows[0]) + height = len(rows) + + for y, row in enumerate(rows): + for x, cell in enumerate(row): + if cell == '.': + continue + + for prev_x, prev_y in grid[cell]: + dx = x - prev_x + dy = y - prev_y + + for potential in ((prev_x-dx, prev_y-dy), (x+dx, y+dy)): + if 0 <= potential[0] < width and 0 <= potential[1] < height: + antinodes.add(potential) + + grid[cell].append((x, y)) + + return sum(1 for _ in antinodes) + +if __name__ == '__main__': + puz = aocd.models.Puzzle(year=2024, day=8) + + # data = puz.examples[0].input_data + data = puz.input_data + + solution = solve(data) + + print(solution) + aocd.submit(solution, year=2024, day=8, part='a') \ No newline at end of file diff --git a/day_08/part_b.py b/day_08/part_b.py new file mode 100644 index 0000000..0dfd029 --- /dev/null +++ b/day_08/part_b.py @@ -0,0 +1,53 @@ +import aocd +import math +import collections +import itertools + +def solve(data): + grid = collections.defaultdict(list) + antinodes = set() + + rows = data.split('\n') + width = len(rows[0]) + height = len(rows) + + for y, row in enumerate(rows): + for x, cell in enumerate(row): + if cell == '.': + continue + + for prev_x, prev_y in grid[cell]: + dx = x - prev_x + dy = y - prev_y + + angle = math.gcd(dx, dy) + dx, dy = dx // angle, dy // angle + + # In the direction of the previous antenna... + for i in itertools.count(step=-1): + if 0 <= (new_x := prev_x + dx*i) < width and 0 <= (new_y := prev_y + dy*i) < height: + antinodes.add((new_x, new_y)) + else: + break + + # In the direction of the current antenna... + for i in itertools.count(step=1): + if 0 <= (new_x := x + dx*i) < width and 0 <= (new_y := y + dy*i) < height: + antinodes.add((new_x, new_y)) + else: + break + + grid[cell].append((x, y)) + + return sum(1 for _ in antinodes) + +if __name__ == '__main__': + puz = aocd.models.Puzzle(year=2024, day=8) + + # data = puz.examples[0].input_data + data = puz.input_data + + solution = solve(data) + + print(solution) + aocd.submit(solution, year=2024, day=8, part='b') \ No newline at end of file