May 8, 2025

Advent of Slowed Days 13 and 14

My deadline for finishing Day 14 of last year’s advent of code is the 20th, but I have, in fact, already finished it. I am not just scraping by now, I am smashing these deadlines. This probably has more to do with nobody in my household being poorly this week rather than any other factors. In fact, between finishing Day 13 and starting Day 14, I even had some time to go back and look at making some efficiency improvements to some slow tests.

Day 13

This was an interesting day, that involved writing two completely different solutions. The actual solution didn’t take much work, but it took me a while as I ended up going off on quite a tangent, as we’ll see in a minute.

So the problem is you have a button that moves a grabber arm a certain amount in the x direction and a certain amount in the y direction. There are in fact two buttons that have different values for how much they move the grabber in those two directions. There is also a target position: the position of the prize. For Part 1 you are told that it will take at most 100 pushes of each button. The wrinkle is that each button has a cost associated with it, and your goal is to reach the prize while minimising the cost. Even as I was writing my solution, I felt I was falling into a trap, but oh well, it didn’t take long.

The approach I took was to get a list of all pairs of numbers where each member of the pair is between 0 and 100 inclusive. I did this with the nice itertools feature cartesian_product:

(0..=100).cartesian_product(0..=100)

And then I sorted these pairs by their cost, using sort_by_key. Then it’s just a case of looping through this iterator until we find a case where those button presses get us the prize. Simple.

Before we get to how Part 2 very predictably totally undermined my whole approach, I want to take a moment to reflect on Rust’s trait system. If you copy the above code into your project and try to run it, it would fail unless you already have use itertools::Itertools at the top of your file. But once you import that, itertools gives extra methods to all your standard library iterators! You don’t need to change anything else, you don’t need to use a special kind of itertools iterator class or anything like that, it just adds methods to your existing iterators. It’s great. (It causes some limitations on how traits work, because of the future compatibility guarantees Rust wants to have, but as an end user, it’s super neat).

Part 2, then. Advent of Code classic move: do the same thing, but now the number is huge. The prize is actually ten trillion units away in each of the x and y directions. And let’s throw away that 100 move limit, obviously. Listing and looping through all the possible moves is clearly out. So what to do?

First things first, let’s figure out what solutions look like. Let’s say we’ve got buttons $A$ and $B$, which move the grabber by $(x_a, y_a)$ and $(x_b, y_b)$ respectively. You’re basically looking for values $a$ and $b$ such that

$$ ax_a +bx_b = x_p\\ ay_a + by_b = y_p $$

Where $(x_p,y_p)$ is the location of the prize. Then we need to find that pair of $a$ and $b$ that minimise the cost of the buttons. But wait! That’s two simultaneous equations with two unknowns: we can just solve this. So do some rearrangement, and voilà: a closed form solution for the number of buttons we need to press. I refactor my Part 1 solution (delete and start again), and check it still works. Now the problem with Part 2 is that ten trillion is a big number. It is, importantly bigger than can be held in a i32 which is the data type I had implicitly assumed in my coords module. So my first attempt at a solution to Part 2 was to just pull the values out of the coords::Coord, cast them all to i64 and do the calculation there. This worked, but it was kind of unsatisfying. I had a few days before the Day 13 deadline passed, so I decided the sensible thing to do was to make the coords module take a generic type parameter for the inner type. So instead of being a pair of i32s, a coords::Coord would, from now on, be a pair of type T. I spent quite a while getting this to work, but I learned a lot (many thanks to the nice folks at the Rust Programming Language Forum for answering all my basic questions).

I got a bit sidetracked at one point because I wanted to add an implementation of the From trait to Coord which would have allowed me to turn a Coord<i32> into a Coord<i64> easily, but I couldn’t quite get this to work how I wanted. The problem is that if I try to provide a blanket implementation for From that maps Coord<T> to Coord<U> (where we have an impl of From for mapping T to U), this flags up a compiler error because there’s already a conflicting implementation of From<T> for T for any T and so if U is T then we’d have two implementations of the same trait and Rust won’t allow that. As I understand it, we don’t currently have a way to add a trait bound that says “where U is not T”, nor any way to say “only pay attention to this if you don’t already have an impl for this trait”. So this was something of a dead end. I got some helpful suggestions to look at adding impls with concrete types using a macro, but in the end I decided not to bother with that for now.1

In the end, the key part of my Part 1 solution looked like this: machines.iter().filter_map(|m| m.solve()).sum(); and the same line of my Part 2 solution looked like this: machines.into_iter().filter_map(|m| m.embiggen_prize().solve()).sum(). I was quite happy with having made the solutions so uniform.

This was also a day when I decided to use a regex library, rather than using nom parser combinator library to ingest the raw data. Why? Mainly because it made a change, and the regex was pretty straightforward.

Performance improvements

As I do these problems, I have a test suite that grows and grows. Some tests are ignored because they take 90 seconds or more to complete. So since I had some time before I could start on Day 14, I decided to see if I couldn’t make some improvements. One thing I could do was remove a lot of cases where I had used .clone() on a Coord. I did this in the early days, but then I realised I could derive Copy and then I can just dereference instead of cloning. I also got around to making use of some parallelism where I could. So Day 6 Part 2 (seeing where I could put obstacles that would cause the guard to go in a loop) was clearly very parallelisable. At first I used par_map but I later changed to using rayon for this (rayon has a parallel filter_map which I needed for Day 7). The modifications were incredibly minor, and my test that does Day 6 Part 2 went from taking 90 seconds to taking 5 seconds.

I also made some changes to Day 7, memoizing a function that gets called a lot. This was simply a matter of adding a crate and then adding the annotation #[memoize]. I used cargo-flamegraph to help figure out what my code was doing here. It was spending a lot of time doing collect so I tried to replace some vector return types with iterators instead. This did seem to make something of a difference. These tweaks, and another use of rayon for some parallelism, got us down from 90 seconds to about 20 seconds for Part 2.

I also had a look at the suggestions from clippy and made most of the changes. I did come across a few that I didn’t like, and changing my clipp config is now something I’m planning to do before I start Day 15.

Day 14

I have actually lost count of the number of says I have used my coords module.2 It’s getting another outing in Day 14.

So we’ve got a bunch of robots who have a position and a momentum attribute; and on each tick they add their momentum to their position. They wrap around the defined area, Asteroids-style, or torus-style, depending on your preferred brand of nerd. The wrapping around I did by doing modular arithmetic on the individual components of the Coord. I thought about trying to implement a piecewise modulo operation as an impl Rem, but I decided I’m not sure it really makes a lot of sense in general, even if it would have been useful here. Part 1 involved running 100 steps forward, and then counting how many robots are in each quadrant of the area. My initial approach to solving this – in hindsight, this is a bad way to go – was to split out the vector of robots into four vectors, one for each quadrant. Then we calculate the “safety factor” by multiplying the lengths of these vectors together. This was pretty straightforward.

Part 2 then required us to find the tick at which the robots assemble themselves into an image of a christmas tree. I looked through the first hundred or so steps, and then realised that there’s something like 10 thousand steps to look through, so I needed a different approach.3

I have tried, in doing these puzzles, to avoid spoilers and to avoid looking at other people’s answers until I’m finished with mine. I must admit though, that this one had me stumped. I couldn’t think how to narrow down which iterations might be christmas trees, so I had a look at a couple of other solutions, although none written in Rust. The key insight I saw that helped me out of my rut was that the safety factor will be low when all the robots are clustered together in one quadrant. So if we loop until the pattern repeats, and then return the lowest safety factor, this is a good candidate for where the picture appears.

Calculating the safety factor at every step turned out to be tricky with my initial way of calculating: in order to create the four quadrant vectors, I need to move the vector of robots, and that means it isn’t available for me when I come to do the next iteration: it’s been moved. So I completely rethought my approach and I added a method to the Robot struct that returns what quadrant it’s in (expressed as a value from an enum). Importantly, I can now get counts of how many robots are in each quadrant using a reference to the vector of robots, so my loop works! I also made use of itertools method counts which basically works like Counter in Python. So I got my minimum value for the safety factor and then printed out an array of . and X to visualise the distribution of robots, and confirm that on the iteration with the lowest safety count, there is a pretty clear image of a christmas tree. Another day done and dusted.


  1. Incidentally, I mentioned in a previous post that I wanted to look at how to make implementing arithmetic operations for referenced values easier, and the solutions I have come across here, too, are to use a macro that writes out a bunch of impls for concrete types. It’s something I’ll look at at some point. ↩︎

  2. I grepped my AoC directory and I believe I’ve used it on 6 of the 14 days I’ve done so far. ↩︎

  3. I double checked the number of steps until the pattern repeats by doing a loop where I add the hash of the vector of robots to a list and then doing one step, return when we hit a hash value we’ve seen: the value is the same as the height times the width of the area. ↩︎

© Seamus Bradley 2021–6

Powered by Hugo & Kiss.