January 20, 2025

Advent of Slowed Days 3 and 4

And here we are, back on track. After getting myself extremely behind schedule (already!) by trying to be too clever on Day 2, I’ve breezed through Days 3 and 4. These two days also demonstrate two Advent of Code classic solution types. Day 3 is a “make the calculation trivial by doing all the work in the parser” solution, and Day 4 is a “parse the input into some kind of grid, then query the grid”.

Day 3 was an opportunity to practice using the nom parser combinator library. I first came across the concept of parser combinators when doing Advent of Code in Haskell last year, and I really like the approach. The idea is you build up little functions that parse chunks of your text, and then you combine them together using functions that return parsers into a big function that parses all of it. So for example, here’s part of my solution to Day 3 (the full code is available here):

fn mul_group(s: &str) -> IResult<&str, i32> {
    let mul_tag = tag("mul");
    let inner_num_group = separated_pair(i32parse, tag(","), i32parse);
    let num_group = delimited(tag("("), inner_num_group, tag(")"));
    let mul_group = tuple((mul_tag, num_group));
    map(mul_group, |(_, (y, z))| z * y)(s)
}

This parser matches a group that looks like mul(123,456) where it will match any pair of numbers separated by a comma, surrounded by brackets, with mul prepended. The tag parser just matches its input. The i32parse parser matches some numeric characters and returns the number they represent. (Sidebar: it’s very silly that the nom number parsers have the same names as the types. I did use nom::character::complete::i32 as i32parse; to avoid the clash). The separated_pair combinator takes three parsers, matches the three in order and returns the output of the first and third. Or rather, it returns a parser that effectively returns the outputs of the first and third arguments to separated_pair. The delimted combinator is sort of the opposite of separated_pair: it takes three parsers and returns only the second one. tuple takes a tuple of parsers and returns a tuple of outputs. And finally map returns a parser that maps the output of one parser through the provided function. In fact, everything I’ve said here is a lie. None of these functions return the output you want: they return an IResult which is a Result (so either Ok(value) or Error(something)) where the value is a pair of the remaining unparsed string and the output of the parser. Wrapping it up like this means you can write your parsers without really worrying about handling errors: something something monad.

I like this approach, once I got the hang of it, it fits with how I think. It’s nice because you can build up your parser bit by bit and you can test the components. It’s a powerful way to build parsers and much nicer than building complicated regexes.

Part 2 also involved a nice example of the power of pattern matching. Essentially, you’re parsing the input, and you need to keep track of two things: some numbers, and some boolean flags (whether to add the numbers to the total or not). So you can’t just run a parser that picks out all the pieces you need and maps them to useful types, because rust won’t let you have different types in the same vector. So the type of things you collect is in fact (Option<i32>, Option<bool>) and when you’re parsing a number it’s (Some(n), None) and when you’re parsing a flag it’s (None, Some(b)). This then allows you to gather up all the data from the input that you need, and then you can do a fold over it, using pattern matching to decide whether we’re updating the accumlated value, or changing the boolean flag.

Day 4 involved an input where the spatial location of the characters mattered. That is, you needed a reliable way to find out what character was, say, directly above a given character. I’m quite pleased with the approach I took, and I will probably turn part of it into a module that I can reuse in later puzzles. The basic idea is to turn the input into a collection of HashSets – one for each letter – where the HashSet contains the coordinates of all the places where that letter is located. So if the input was:

XMAS
MZZZ
AZZZ
SZZZ

Then the x set contains (0,0), the m set contains (0,1) and (1,0) and so on. Getting the sets from the input involves judicious use of split, enumerate, map, chars and a function to insert into the right set. You would probably want to do this by using a HashMap to associate keys with the values that can appear in the grid, but because there were only four characters we cared about, I just did it by hand in a struct:

struct LetterCoords {
    pub x: HashSet<Coord>,
    pub m: HashSet<Coord>,
    pub a: HashSet<Coord>,
    pub s: HashSet<Coord>,
}

Oh yeah, I also made a Coord struct with methods to easily get the coordinate directly above me and so on. I implemented Add and Mul just like in all the tutorials on traits. With this structure, part one boils down to creating a function that returns a boolean depending on if a certain set of conditions hold: this is an X, there is a M one step in that direction, there is an A two steps in that direction, and so on. Do that for each direction, do that for each X, count up the total. And part two is similar except the predicates are different and you iterate over the As instead.

After how much trouble day 2 caused me, it’s pleasing I managed to solve these two days a little quicker. I am now back on track. My day 4 deadline is the 22nd, so I will come back to start solving day 5 on the 23rd.

© Seamus Bradley 2021–6

Powered by Hugo & Kiss.