-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
122 lines (98 loc) · 2.94 KB
/
__init__.py
File metadata and controls
122 lines (98 loc) · 2.94 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
112
113
114
115
116
117
118
119
120
121
122
from typing import List, Optional, Tuple
from aocpy import BaseChallenge
from dataclasses import dataclass
import math
from collections import deque
CHECKER_POINTS = {
")": 3,
"]": 57,
"}": 1197,
">": 25137,
}
AC_POINTS = {
")": 1,
"]": 2,
"}": 3,
">": 4,
}
@dataclass
class Chunk:
text: str
def is_corrupted(self) -> Tuple[bool, Optional[str]]:
stack = deque()
for char in self.text:
if char == "(":
stack.append(")")
elif char == "[":
stack.append("]")
elif char == "{":
stack.append("}")
elif char == "<":
stack.append(">")
elif char == ")" or char == "]" or char == "}" or char == ">":
r = stack.pop()
if r != char:
return True, char
else:
raise ValueError(f"unknown character in chunk string ({char=})")
return False, None
def complete(self) -> str:
stack = deque()
output = ""
n = 0
while True:
char = None
if n < len(self.text):
char = self.text[n]
if len(stack) == 0 and char is None:
break
if char is None:
output += stack.pop()
elif char == "(":
stack.append(")")
elif char == "[":
stack.append("]")
elif char == "{":
stack.append("}")
elif char == "<":
stack.append(">")
elif char == ")" or char == "]" or char == "}" or char == ">":
r = stack.pop()
if r != char:
raise ValueError(
f"cannot correct corrupted chunk (wanted {r}, got {char})"
)
else:
raise ValueError(f"unknown character in chunk string ({char=})")
n += 1
return output
def parse(instr: str) -> List[Chunk]:
return [Chunk(x) for x in instr.strip().splitlines()]
class Challenge(BaseChallenge):
@staticmethod
def one(instr: str) -> int:
chunks = parse(instr)
score = 0
for chunk in chunks:
is_corrupted, illegal_character = chunk.is_corrupted()
if is_corrupted:
score += CHECKER_POINTS[illegal_character]
return score
@staticmethod
def two(instr: str) -> int:
chunks = parse(instr)
def f(x):
y, _ = x.is_corrupted()
return not y
chunks = list(filter(f, chunks))
points = []
for chunk in chunks:
extra = chunk.complete()
n = 0
for char in extra:
n *= 5
n += AC_POINTS[char]
points.append(n)
points = list(sorted(points))
median = points[math.floor(len(points) / 2)]
return median