Rules: no spoilers.
The other rules are made up as we go along.
Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.
Rules: no spoilers.
The other rules are made up as we go along.
Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.
Day 3: Gear Ratios
Scheme code and explanations
To avoid annoying special cases for dealing with reading past the edges of the schematic, I start by adding one cell of padding on all sides.
I’m also going to define a few utility functions. The
schematic-pos
function reads what’s on the x,y position of the schematic, and is here to compensate for Scheme being awkward for dealing with two-dimensional structures. The two others check whether some position is a symbol (other than.
) or a digit.I want a list of all positions of symbols in the schematic, so I can check them for adjacent numbers. I could also have gone with a list of numbers instead, but symbols seemed easier to find adjacencies for.
This produces a list of
(x y)
pairs, one for each symbol. Finding adjacent numbers is a bit tricky: Since there are three relevant positions above and below the symbol’s own position, there could be one or two numbers above or below, and if there are two, then I might be reading the same number twice. I accept this, and keep the numbers in anlset
(which means that a duplicate simply won’t be inserted). The number reader itself produces triples on the form(x y n)
, wherex
is the position of the first character in the number, andn
is a string containing the number itself. The coordinates are stored to ensure that if there are several instances of the same number in different positions in the schematic, they get treated separately.From here, solving the two parts is easy. For part 1, we get all the lists of number adjacencies and unpack them into a single list:
For part 2, we need a list of gears. We can just get all the symbols, filter out everything that isn’t a
*
, and then filter out everything that doesn’t have exactly two adjacencies.I could probably have written nicer code if I weren’t still a bit sick (though I’m getting better!). However, the moment I realized this one would be about mucking around with two-dimensional structures, I knew Scheme was going to be a bit awkward. But here you have it.