Repository navigation
Expand file tree
/
Copy pathday10.py
More file actions
executable file
·111 lines (97 loc) · 2.23 KB
/
Copy pathday10.py
File metadata and controls
executable file
·111 lines (97 loc) · 2.23 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env python3
test_input = """\
[({(<(())[]>[[{[]{<()<>>
[(()[<>])]({[<{<<[]>>(
{([(<{}[<>[]}>{[]{[(<()>
(((({<>}<{<{<>}{[]{[]{}
[[<[([]))<([[{}[[()]]]
[{[{({}]{}}([{[{{{}}([]
{<[[]]>}<{[{[{[]{()[[[]
[<(<(<(<{}))><([]([]()
<{([([[(<>()){}]>(<<{{
<{([{{}}[<[[[<>{}]]]>[]]
"""
matches = {
'{': '}',
'}': '{',
'[': ']',
']': '[',
'<': '>',
'>': '<',
'(': ')',
')': '(',
}
def bad(line):
stack = []
for c in line:
if c in ('(', '{', '[', '<'):
stack.append(c)
elif c in matches:
b = stack.pop()
if matches[c] != b:
return c
return False
scores = {
')': 3,
']': 57,
'}': 1197,
'>': 25137,
}
def score(input):
n = 0
for line in input.splitlines():
c = bad(line)
if c:
n+= scores[c]
return n
got = score(test_input)
want = 26397
if got != want:
raise Exception('score(test_input): got %d, want %d' % (got, want))
with open('inputs/day10.input') as f:
sc = score(f.read())
print('Day 10 Part 1 => %d' % sc) # => 240123
### Part 2
cscores = {
')': 1,
']': 2,
'}': 3,
'>': 4,
}
def goodness(line):
stack = []
for c in line:
if c in ('(', '{', '[', '<'):
stack.append(c)
elif c in matches:
b = stack.pop()
if matches[c] != b:
return False
stack.reverse()
closers = [matches[c] for c in stack]
n = 0
for x in closers:
n = n*5 + cscores[x]
return n
wants = {
'[({(<(())[]>[[{[]{<()<>>': 288957,
'[(()[<>])]({[<{<<[]>>(': 5566,
'(((({<>}<{<{<>}{[]{[]{}': 1480781,
'{<[[]]>}<{[{[{[]{()[[[]': 995444,
'<{([{{}}[<[[[<>{}]]]>[]]': 294,
}
for input, want in wants.items():
got = goodness(input)
if got != want:
raise Exception('goodness(%s): got %d, want %d' % (input, got, want))
def best(input):
sc = list(filter(bool, map(goodness, input.splitlines())))
sc.sort()
return sc[len(sc)//2]
got = best(test_input)
want = 288957
if got != want:
raise Exception('best(test_input): got %d, want %d' % (got, want))
with open('inputs/day10.input') as f:
sc = best(f.read())
print('Day 10 Part 2 => %d' % sc) # => 3260812321