Module advent_of_code_2021::day_10 [−][src]
Expand description
This is my solution for Advent of Code - Day 10 - Syntax Scoring
Today was about matching different types of braces, firstly (part one) to check that the braces matched, and secondly (part two) where closing braces had been missed off the end of the string to close them. Implementing the state as a stack of characters seemed sensible. An opening brace triggers putting the expected closing brace on the stack, a closing brace pops the expected brace off the stack and returns an error if it doesn’t match. Anything left on the stack at the end is returned as the required characters to ‘autocomplete’ the rest of the line. I originally implemented this as putting the opening brace on the stack, but that required doing the mapping from opening to closing brace character both when checking for a match and when returning outstanding characters. It was cleaner to do the mapping upfront.
check_line do most of the work for both parts. It was a good opportunity to use Rust’s Result type, and I
implemented a custom enum ParseError to capture the errors due to syntax, vs the errors I needed to include
to satisfy edge cases that weren’t in the puzzle input - namely characters that weren’t any of the 8 braces, and
the case where there is one or more closing braces encountered when the stack is empty. sum_errors wraps
check_line for part one, filtering out ny lines that don’t return a ParseError::MISMATCH, mapping those
to the correct score, and summing the results. score_line_autocomplete takes the characters returned from a
successfully parsed line and folds them into the expected score. median_autocomplete_score handles the
plumbing of getting the list of successful check_line results, mapping them to the autocomplete score and
returning the median score required for part two’s puzzle result.
One final piece of trivia, I looked into using the characters’ unicode points to avoid using a hash map, but they
were not consistent. ( and ) are consecutive, but the others are all separated by one character.
println!("{}", "()[]{}<>".chars().map(|c| c as usize).join(", "));
// 40, 41, 91, 93, 123, 125, 60, 62Enums
Used to indicate an error when parsing strings of braces
Functions
Given a string, either return the list of closing braces needed to completely match the opening braces in order,
or return a ParseError if a closing brace that doesn’t match the expected value at any point in the string.
Find all the lines in the input that are valid, work out the autocomplete score for each, and return the median score.
The entry point for running the solutions with the ‘real’ puzzle input.
Given the list of braces needed to complete a string, fold them into the autocomplete score
Find all the lines in the input that return a mismatch error and sum a score based on the character that was incorrect.
