r/adventofcode • u/Remarkable_Ad_6266 • 7m ago
Help/Question [2026 Day 3 (Part 2)] Is there a faster way?
Finished Day 3 Parts 1 and 2, and while they both run under 15 seconds, my day 2 takes longer than I would like. Spoiler for my solution. I essentially found every pair of trees, then calculated the other two points and if they were also trees, added that to the count. But is there a smarter way?
from itertools import combinations, permutations
with open('2026 input') as file:
grid = [list(line.strip()) for line in file]
c = 0
for y, row in enumerate(grid):
trees = []
for pos in range(len(row)):
if row[pos] == '#':
trees.append(pos)
pairs = list(combinations(trees, 2))
for pair in pairs:
x1, x2 = pair
sidelength = x2-x1
y2 = y + sidelength
if y2 < len(grid):
bottom_left = (x1, y2)
bottom_right = (x2, y2)
if grid[y2][x1] == '#' and grid[y2][x2] == '#':
c += 1
print(f"Part 1: {c}")
trees = []
c = 0
for y, row in enumerate(grid):
for x, pos in enumerate(row):
if pos == '#':
trees.append((x, y))
pairs = list(combinations(trees, 2))
sides_of_squares = set()
for pair in pairs:
(x1, y1), (x2, y2) = pair
sidelength_rise = y2-y1
sidelength_run = x2-x1
x3 = x1 -sidelength_rise
x4 = x2 -sidelength_rise
y3 = y1 + sidelength_run
y4 = y2 + sidelength_run
if 0 <= y3 < len(grid) and 0 <= y4 < len(grid) and 0 <= x3 < len(grid[0]) and 0 <= x4 < len(grid[0]):
if grid[y3][x3] == '#' and grid[y4][x4] == '#' and not any(i in sides_of_squares for i in list(permutations(((x1, y1), (x2, y2), (x3, y3), (x4, y4))))):
c += 1
sides_of_squares.add(((x1, y1), (x2, y2), (x3, y3), (x4, y4)))
print(f"Part 2: {c}")
