This was an interesting puzzle with a nice solution in Dusa, but I don’t find myself too inspired to say a lot about it or writing up the whole thing for this one.
The solution is longer than it needs to be: I calculate the width of the grid in a silly way, really I should have just fed the width in as a fact, but instead I use the same possibility trick I used with a less-than relation and both of the Day 2 solutions: each column could be the width, but if a column is smaller than another column it’s definitely not.
I added an commented translation for what the core logic of the Part 1 solution is doing. To me it seems quite pleasant! I picked up a couple of the techniques I used from Adam Smith’s Map Generation Speedrun for Answer Set Programming.
**delta 1.
delta 0.
delta -1.
*# The number N has an adjacent symbol when*
numWithAdjacentSymbol Line Start is N :-
*# There's a number at (Line, Start)*
numAt Line Start is N,
*# And that number extends to (Line, Col)*
numPrefixAt Line Start Col is _,
*# And for (AdjCol, AdjLine) within 1 square of (Line, Col)*
delta Dx, delta Dy,
AdjCol == plus Dx Col,
AdjLine == plus Dy Line,
*# There's a symbol at (AdjLine, AdjCol)*
charAt AdjLine AdjCol is Ch,
isSymbol Ch is true.**
For both Part 1 and Part 2, I decided not to bother trying to do the summing-up part in Dusa — I think it would have been possible but a bit silly. Instead I queried all the numWithAdjacentSymbol facts and added up their values for the solution.
Here’s the program on dusa.rocks
Here’s the program on StackBlitz
This is a really nice solution, because I can extend numWithAdjacentSymbol just a bit to track both the line and number that has an adjacent character, but also the location of that adjacent character and what the adjacent character is.
**numWithAdjacentSymbol Line Start AdjLine AdjCol is (pair N Ch) :-**
The thing that Datalog languages do effortlessly that’s a pain in the ass for other languages (IMO) is re-associate that information: it’s a four-liner to find all the gears adjacent to two distinct numbers.
**gear Line Col is (times N1 N2) :-
numWithAdjacentSymbol Line1 Col1 Line Col is (pair N1 "*"),
numWithAdjacentSymbol Line2 Col2 Line Col is (pair N2 "*"),
pair Line1 Col1 != pair Line2 Col2.**
(This solution will also call a * adjacent to three symbols a gear, incorrectly. My actual solution defends against that, but I didn’t check whether that defensiveness was necessary.)