Advent of Code 2024, Day 8
In part 2, I lost time because I didn’t include the antinodes on the antennas themselves at first.
Part 1
import sys
def valid_location(lines, i, j):
return 0 <= i < len(lines) and 0 <= j < len(lines[i])
def get_antinodes(lines, locations):
r = set()
for ai, aj in locations:
for bi, bj in locations:
if (ai, aj) == (bi, bj): continue
diffi = bi-ai
diffj = bj-aj
if valid_location(lines, ai-diffi, aj-diffj):
r.add((ai-diffi, aj-diffj))
if valid_location(lines, bi+diffi, bj+diffj):
r.add((bi+diffi, bj+diffj))
return r
with open(sys.argv[1]) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
locations = {}
for i in range(len(lines)):
for j in range(len(lines[i])):
letter = lines[i][j]
if letter == ".": continue
if letter in locations:
locations[letter].add((i, j))
else:
locations[letter] = {(i, j)}
antinodes = set()
for locations in locations.values():
antinodes.update(get_antinodes(lines, locations))
print(len(antinodes))
Part 2
import sys
def valid_location(lines, i, j):
return 0 <= i < len(lines) and 0 <= j < len(lines[i])
def get_antinodes(lines, locations):
r = set()
for ai, aj in locations:
for bi, bj in locations:
if (ai, aj) == (bi, bj): continue
diffi = bi-ai
diffj = bj-aj
n = 0
while valid_location(lines, ai+n*diffi, aj+n*diffj):
r.add((ai+n*diffi, aj+n*diffj))
n -= 1
n = 1
while valid_location(lines, ai+n*diffi, aj+n*diffj):
r.add((ai+n*diffi, aj+n*diffj))
n += 1
return r
with open(sys.argv[1]) as f:
lines = f.readlines()
lines = [line.strip() for line in lines]
locations = {}
for i in range(len(lines)):
for j in range(len(lines[i])):
letter = lines[i][j]
if letter == ".": continue
if letter in locations:
locations[letter].add((i, j))
else:
locations[letter] = {(i, j)}
antinodes = set()
for locations in locations.values():
antinodes.update(get_antinodes(lines, locations))
print(len(antinodes))
2024-12-13