diff --git a/2024/day8/main.py b/2024/day8/main.py index 27edf39..ed3cdbb 100644 --- a/2024/day8/main.py +++ b/2024/day8/main.py @@ -11,8 +11,8 @@ y_bound: int = len(data) x_bound: int = len(data[0].strip()) for y, line in enumerate(data): - for x, char in enumerate(line): - if char not in ['.', '\n']: + for x, char in enumerate(line.strip()): + if char not in ['.']: if char not in groups: groups[char] = [Vector(x, y)] else: @@ -22,6 +22,15 @@ for y, line in enumerate(data): def in_bounds(v: Vector) -> bool: return v.x >= 0 and v.x < x_bound and v.y >= 0 and v.y < y_bound +def print_nodes(antinodes: list[Vector]) -> None: + datac = data.copy() + for antinode in antinodes: + datac[antinode.y] = datac[antinode.y][:antinode.x] + '#' + datac[antinode.y][antinode.x + 1:] + + for line in datac: + print(line, end='') + print() + antinodes = [] for char, group in groups.items(): for i, A in enumerate(group): @@ -36,13 +45,33 @@ for char, group in groups.items(): if antinode_pos2 not in antinodes and in_bounds(antinode_pos2): antinodes.append(antinode_pos2) -for antinode in antinodes: - data[antinode.y] = data[antinode.y][:antinode.x] + '#' + data[antinode.y][antinode.x + 1:] +print_nodes(antinodes) -for line in data: - print(line, end='') - -print(f'\nPart 1: {len(antinodes)}') +print(f'Part 1: {len(antinodes)}') # Part 2 +antinodes = [] +for char, group in groups.items(): + for i, A in enumerate(group): + for B in group[i + 1:]: + + dist = B - A + antinode_pos = A + dist + while in_bounds(antinode_pos): + if antinode_pos not in antinodes: + antinodes.append(antinode_pos) + + antinode_pos += dist + + dist = dist.inverse() + antinode_pos = B + dist + while in_bounds(antinode_pos): + if antinode_pos not in antinodes: + antinodes.append(antinode_pos) + + antinode_pos += dist + +print_nodes(antinodes) + +print(f'Part 2: {len(antinodes)}') diff --git a/2024/day8/test2.text b/2024/day8/test2.text new file mode 100644 index 0000000..023061c --- /dev/null +++ b/2024/day8/test2.text @@ -0,0 +1,10 @@ +T......... +...T...... +.T........ +.......... +.......... +.......... +.......... +.......... +.......... +.......... \ No newline at end of file diff --git a/2024/day8/vector.py b/2024/day8/vector.py index c96d4a6..1134910 100644 --- a/2024/day8/vector.py +++ b/2024/day8/vector.py @@ -19,6 +19,9 @@ class Vector: def abs(self) -> Self: return Vector(abs(self.x), abs(self.y)) + def inverse(self) -> Self: + return Vector(-self.x, -self.y) + def __str__(self) -> str: return f'{self.x}, {self.y}'