Python
Chose to do part 1 and 2 very differently.
- Part 1 runs checks pairs of trees along the diagonal to see if they form opposite corners of a square.
- Part 2 turns every segment formed by 2 trees by 90 degrees to see if it is the side of a square.
click to see code
from collections import defaultdict
from itertools import combinations
def part1(data: str):
trees = set() # set of all trees
trees_on_diag = defaultdict(list) # list of trees grouped by their diagonal
for i, line in enumerate(data.splitlines()):
for j, ch in enumerate(line):
if ch == '#':
trees.add((i, j))
# trees can be grouped using a single integer into its down-right diagonal
# if you use i-j, you get:
# 0 -1 -2 -3
# 1 0 -1 -2
# 2 1 0 -1
# 3 2 1 0
trees_on_diag[i-j].append((i, j))
squares = 0
# for trees in the same diagonal, try combinations of each and see if they form opposite corners of a square
for diag_trees in trees_on_diag.values():
for (x1, y1), (x2, y2) in combinations(diag_trees, r=2):
if (x1, y2) in trees and (x2, y1) in trees:
squares += 1
return squares
def part2(data: str):
trees = set() # set of all trees
for i, line in enumerate(data.splitlines()):
for j, ch in enumerate(line):
if ch == "#":
trees.add((i, j))
squares = 0
# for all tree combinations, we will assume that they form a side of square and check if that is valid
for t1, t2 in combinations(trees, r=2):
i1, j1 = t1
i2, j2 = t2
# the difference between the trees in i, j dimensions
di, dj = (i1 - i2), (j1 - j2)
# since we don't know which direction that 90d angle should be to continue the square, we will try both ways
turns = (
(-dj, di), # left hand 90d turn
(dj, -di), # right hand 90d turn
)
for turn_i, turn_j in turns:
# new points after turning from both original point (you could also turn twice)
t3, t4 = (i1 + turn_i, j1 + turn_j), (i2 + turn_i, j2 + turn_j)
# if any points are not trees, we go on
if t3 not in trees:
continue
if t4 not in trees:
continue
squares += 1
# since we tried to make every segment a square, we counted each square 4 times
# this is because each side of the square will find it once in one of its turns
return squares // 4
- all the squares drawn together