advent_of_code_2021

My attempts to work through the 2021 Advent of Code problems.
git clone https://git.eamoncaddigan.net/advent_of_code_2021.git
Log | Files | Refs | README | LICENSE

commit 605b631b1e31767e3772224d11f14bb18c91aedd
parent 0b23461c5d9d68fc0084956f2eb70b31822ca1c1
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date:   Fri, 10 Dec 2021 08:33:39 -0500

Soution to day 10, part 1

Diffstat:
Aday10_part1.py | 66++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 66 insertions(+), 0 deletions(-)

diff --git a/day10_part1.py b/day10_part1.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +"""Advent of Code 2021, day 10 (part 1): Syntax Scoring +For part 1, we are finding 'corrupted' lines from the navigation subsystem +(ones that have mismatched brackets) and scoring them.""" + +# I'm not going to bother trying to use pandas for this one. + +from utils import get_puzzle_input + +EXAMPLE_INPUT = \ +"""[({(<(())[]>[[{[]{<()<>> +[(()[<>])]({[<{<<[]>>( +{([(<{}[<>[]}>{[]{[(<()> +(((({<>}<{<{<>}{[]{[]{} +[[<[([]))<([[{}[[()]]] +[{[{({}]{}}([{[{{{}}([] +{<[[]]>}<{[{[{[]{()[[[] +[<(<(<(<{}))><([]([]() +<{([([[(<>()){}]>(<<{{ +<{([{{}}[<[[[<>{}]]]>[]] +""" + +def convert_input_to_list(input_string): + """Convert the puzzle input to a list of strings""" + return input_string.rstrip('\n').split('\n') + +def is_open_bracket(bracket): + """Returns True iff the character is an open bracket""" + return bracket in '([{<' + +def match_bracket(bracket): + """Given an open bracket, return the matching close bracket""" + return {'(': ')', '[': ']', '{': '}', '<': '>'}[bracket] + +def score_bracket(bracket): + """Given a close bracket, return its associated score""" + return {')': 3, ']': 57, '}': 1197, '>': 25137}[bracket] + +def score_line(line): + """Return the 'score' of a corrupted line, or 0 for lines that are not + corrupt""" + # Going with a straightforward solution here: using a stack, pushing open + # brackets and popping when we find close brackets. If we have the wrong + # close bracket, return a score for the bracket we have, otherwise we + # return 0. + bracket_stack = [] + for bracket in line: + if is_open_bracket(bracket): + bracket_stack.append(bracket) + else: + if match_bracket(bracket_stack.pop()) != bracket: + return score_bracket(bracket) + return 0 + +def solve_puzzle(input_string): + """Return the numeric solution to the puzzle""" + return sum([score_line(l) for l in convert_input_to_list(input_string)]) + +def main(): + """Run when the file is called as a script""" + assert solve_puzzle(EXAMPLE_INPUT) == 26397 + print("Score for corrupted lines:", + solve_puzzle(get_puzzle_input(10))) + +if __name__ == "__main__": + main()