-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathday13.py
executable file
·67 lines (48 loc) · 1.3 KB
/
day13.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#!/usr/bin/env python3
import sys
def transpose(grid):
return list(map(''.join, zip(*grid)))
def count_differences(a, b):
diff = 0
for linea, lineb in zip(a, b):
diff += sum(chara != charb for chara, charb in zip(linea, lineb))
if diff > 1:
break
return diff
def find_reflections(grid):
height = len(grid)
perfect = imperfect = 0
for size in range(1, height // 2 + 1):
a = grid[:size]
b = grid[2 * size - 1:size - 1:-1]
diff = count_differences(a, b)
if diff == 0:
perfect = size
elif diff == 1:
imperfect = size
if perfect and imperfect:
break
a = grid[height - 2 * size:height - size]
b = grid[height - 1:height - size - 1:-1]
diff = count_differences(a, b)
if diff == 0:
perfect = height - size
elif diff == 1:
imperfect = height - size
if perfect and imperfect:
break
return perfect, imperfect
# Open the first argument as input or use stdin if no arguments were given
fin = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
with fin:
grids = fin.read().split('\n\n')
ans1 = ans2 = 0
for g in map(str.splitlines, grids):
perfect, imperfect = find_reflections(g)
ans1 += 100 * perfect
ans2 += 100 * imperfect
perfect, imperfect = find_reflections(transpose(g))
ans1 += perfect
ans2 += imperfect
print('Part 1:', ans1)
print('Part 2:', ans2)