File tree 1 file changed +9
-4
lines changed 1 file changed +9
-4
lines changed Original file line number Diff line number Diff line change @@ -18,21 +18,24 @@ def neighbours(pos: Vec2) -> list[Vec2]:
18
18
19
19
20
20
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 ))
25
24
26
25
27
26
def sides (region : set [tuple ]) -> int :
27
+ # gather fences by the direction they are facing
28
28
fences = defaultdict (list )
29
29
for pos in region :
30
30
for n , d in Dir .map_nswe (neighbours (pos )).items ():
31
31
if n not in region :
32
32
fences [d ].append (pos )
33
+
34
+ # sort fences by y coord if facing north/south, or x coord for east/west
33
35
for d , fs in fences .items ():
34
36
fences [d ] = sorted (fs , key = lambda f : f [::- 1 ] if d in {Dir .N , Dir .S } else f )
35
37
38
+ # calculate the number of distinct sides facing each direction
36
39
num_sides = 0
37
40
dirmap = {
38
41
Dir .N : Dir .E ,
@@ -43,6 +46,8 @@ def sides(region: set[tuple]) -> int:
43
46
for d , fs in fences .items ():
44
47
num_sides += 1
45
48
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
46
51
if (Vec2 (f1 ) + dirmap [d ]).as_tuple () != f2 :
47
52
num_sides += 1
48
53
You can’t perform that action at this time.
0 commit comments