Skip to content

Commit

Permalink
[2024/8] comments and tidying
Browse files Browse the repository at this point in the history
  • Loading branch information
StarlitGhost committed Dec 8, 2024
1 parent 521f316 commit 2fde61d
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions 2024/8/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,50 +2,64 @@
from GhostyUtils.grid import Grid
from GhostyUtils.vec2 import Vec2
from itertools import combinations
import math


def antinodes(a: tuple, b: tuple, grid: Grid, resonates: bool = False) -> list[tuple]:
# calculates and returns a list of antinode positions from a pair of antenna
def calc_antinodes(a: tuple, b: tuple, grid: Grid, resonates: bool = False) -> list[tuple]:
a, b = Vec2(a), Vec2(b)
v = b - a
v = b - a # vector between a & b
# print(f"a: {a} b: {b} v: {v} | {a - v} {b + v}")

nodes = []

# p1
if not resonates:
aa = (a - v).as_tuple()
ab = (b + v).as_tuple()
aa = (a - v).as_tuple() # project v back from a
ab = (b + v).as_tuple() # project v forward from b
nodes += [aa] if grid.in_bounds(aa) else []
nodes += [ab] if grid.in_bounds(ab) else []

# p2
else:
# add the antenna positions themselves
nodes += [a.as_tuple(), b.as_tuple()]

# repeatedly project v back from a until we go out of bounds
pos = a - v
while grid.in_bounds(pos):
nodes += [pos.as_tuple()]
pos -= v

# repeatedly project v forward from b until we go out of bounds
pos = b + v
while grid.in_bounds(pos):
nodes += [pos.as_tuple()]
pos += v

return nodes


def main():
grid = Grid(aoc.read_lines())
antennas = {}

for element, pos in grid.by_cell():
if element != '.':
antennas.setdefault(element, []).append(pos)
# find all the antennas, and store them as {frequency: [positions]}
for freq, pos in grid.by_cell():
if freq != '.':
antennas.setdefault(freq, []).append(pos)

antinode_positions = set()

# calculate antinodes for each antenna frequency
for antenna, positions in antennas.items():
for combo in combinations(positions, 2):
antinode_positions.update(antinodes(*combo, grid))

antinode_positions.update(calc_antinodes(*combo, grid))
print(f"p1: {len(antinode_positions)}")

# calculate antinodes for each antenna frequency, with resonance
for antenna, positions in antennas.items():
for combo in combinations(positions, 2):
antinode_positions.update(antinodes(*combo, grid, resonates=True))
antinode_positions.update(calc_antinodes(*combo, grid, resonates=True))
print(f"p2: {len(antinode_positions)}")


Expand Down

0 comments on commit 2fde61d

Please sign in to comment.