Skip to content

Commit c395ecd

Browse files
committed
[2024/12] tidying and comments
1 parent 959be4d commit c395ecd

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

2024/12/script.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,24 @@ def neighbours(pos: Vec2) -> list[Vec2]:
1818

1919

2020
def perimeter(region: set[tuple]) -> int:
21-
p = 0
22-
for pos in region:
23-
p += sum(n not in region for n in neighbours(pos))
24-
return p
21+
# for each position in the region,
22+
# count how many of its neighbours are outside the region
23+
return sum(n not in region for pos in region for n in neighbours(pos))
2524

2625

2726
def sides(region: set[tuple]) -> int:
27+
# gather fences by the direction they are facing
2828
fences = defaultdict(list)
2929
for pos in region:
3030
for n, d in Dir.map_nswe(neighbours(pos)).items():
3131
if n not in region:
3232
fences[d].append(pos)
33+
34+
# sort fences by y coord if facing north/south, or x coord for east/west
3335
for d, fs in fences.items():
3436
fences[d] = sorted(fs, key=lambda f: f[::-1] if d in {Dir.N, Dir.S} else f)
3537

38+
# calculate the number of distinct sides facing each direction
3639
num_sides = 0
3740
dirmap = {
3841
Dir.N: Dir.E,
@@ -43,6 +46,8 @@ def sides(region: set[tuple]) -> int:
4346
for d, fs in fences.items():
4447
num_sides += 1
4548
for f1, f2 in zip(fs, fs[1:]):
49+
# if two fences in the list aren't directly next to each other,
50+
# we found a new side
4651
if (Vec2(f1) + dirmap[d]).as_tuple() != f2:
4752
num_sides += 1
4853

0 commit comments

Comments
 (0)