Advent of Code 2021 - Day 10
Here is my solution of day 10. As soon as I saw those bracket I thought of using a stack.
This day's effort wasn't too bad compared to some of the previous ones. I still have not sat down to solve day 8. I will get to it after attempting at day 11.
CORRUPTION_POINTS = {
")": 3,
"]": 57,
"}": 1197,
">": 25137
}
AUTOCOMPLETE_POINTS = {
")": 1,
"]": 2,
"}": 3,
">": 4
}
PAIRS = {
"(": ")",
"{": "}",
"[": "]",
"<": ">"
}
if __name__ == "__main__":
with open("input.txt", "r") as f:
lines = f.read().split("\n")
illegal_character_count = {}
incomplete_lines = []
autocomplete_scores = []
for l in lines:
stack = list()
is_corrupted = False
for bracket in l:
if bracket in PAIRS.keys():
stack.append(bracket)
if bracket in PAIRS.values():
if PAIRS[stack.pop()] != bracket:
illegal_character_count[bracket] = illegal_character_count.get(
bracket, 0) + 1
is_corrupted = True
if not is_corrupted:
autocomplete_brackets = [
PAIRS[opening_bracket] for opening_bracket in reversed(stack)
]
score = 0
for bracket in autocomplete_brackets:
score = (score * 5) + AUTOCOMPLETE_POINTS[bracket]
autocomplete_scores.append(score)
total_points = sum([v * CORRUPTION_POINTS[k] for k, v in illegal_character_count.items()])
autocompleted_scores = sorted(autocomplete_scores)
middle_score = autocompleted_scores[len(autocompleted_scores) // 2]
print(f"Result for Part 1: {total_points}")
print(f"Result for Part 2: {middle_score}")