Skip to content

Instantly share code, notes, and snippets.

@object
Created December 8, 2024 08:36
Show Gist options
  • Save object/7fd2eab653eb2261b8c8ca0a08a6f7a2 to your computer and use it in GitHub Desktop.
Save object/7fd2eab653eb2261b8c8ca0a08a6f7a2 to your computer and use it in GitHub Desktop.
Advent of Code 2024, day 08
import sys
from itertools import combinations
sys.setrecursionlimit(10**6)
with open("./data/input08.txt") as inputFile:
input = inputFile.read().splitlines()
antennas = {}
for r in range(len(input)):
for c in range(len(input[r])):
if input[r][c] != '.':
antenna_type = input[r][c]
if not(antenna_type in antennas):
antennas[antenna_type] = []
antennas[antenna_type].append((r,c))
antenna_pairs = {}
for antenna_type in antennas.keys():
pairs = list(combinations(antennas[antenna_type], 2))
antenna_pairs[antenna_type] = pairs
# Part 1:
antinodes = set()
for antenna_type in antenna_pairs.keys():
pairs = antenna_pairs[antenna_type]
for pair in pairs:
(a1, a2) = pair
(r1, c1) = a1
(r2, c2) = a2
nr1 = min(r1, r2) - abs(r1 - r2)
nc1 = 0
if r1 < r2:
if c1 < c2: nc1 = c1 - abs(c1 - c2)
elif c1 > c2: nc1 = c1 + abs(c1 - c2)
else: nc1 = c1
elif r1 > r2:
if c1 < c2: nc1 = c1 + abs(c1 - c2)
elif c1 > c2: nc1 = c1 - abs(c1 - c2)
else: nc1 = c1
else:
nc1 = min(c1, c2) - abs(c1 - c2)
nr2 = max(r1, r2) + abs(r1 - r2)
nc2 = 0
if nc1 < min(c1, c2):
nc2 = max(c1, c2) + abs(c1 - c2)
else:
nc2 = min(c1, c2) - abs(c1 - c2)
if nr1 in range(len(input)) and nc1 in range(len(input[0])):
antinodes.add((nr1, nc1))
if nr2 in range(len(input)) and nc2 in range(len(input[0])):
antinodes.add((nr2, nc2))
res = len(antinodes)
print(res)
# Part 2:
antinodes = set()
for antenna_type in antenna_pairs.keys():
pairs = antenna_pairs[antenna_type]
for pair in pairs:
(a1, a2) = pair
r1 = a1[0] if a1[0] < a2[0] else a2[0] if a1[0] > a2[0] else a1[0]
c1 = a1[1] if a1[0] < a2[0] else a2[1] if a1[0] > a2[0] else a1[1]
r2 = a2[0] if a1[0] < a2[0] else a1[0] if a1[0] > a2[0] else a2[0]
c2 = a2[1] if a1[0] < a2[0] else a1[1] if a1[0] > a2[0] else a2[1]
if r1 == r2:
for c in range(len(input[0])):
antinodes.add((r1, c))
else:
for r in range(len(input)):
if r == r1: antinodes.add((r1, c1))
elif r == r2: antinodes.add((r2, c2))
elif (abs(r - r1) * abs(c2 - c1)) % abs(r2 - r1) == 0:
diff = (abs(r - r1) * abs(c2 - c1)) // (r2 - r1)
if r < r1 and c1 < c2 or r > r1 and c1 > c2:
c = c1 - diff
else:
c = c1 + diff
if r in range(len(input)) and c in range(len(input[0])):
antinodes.add((r, c))
else:
d = abs(c2 - c1) % abs(r2 - r1)
res = len(antinodes)
print(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment