Day 03

Day 03, part 1

Discussion

Looks like a regular expression task. Doing this in perl, it's a snap:

perl -0ne '$ttl = 0; while (/mul\((\d{1,3}),(\d{1,3})\)/g) { $ttl += $1 * $2 }; print qq(Total: $ttl\n);' src/data/03/actual.txt
Total: 178538786
							

I know xslt and xpath have great support for regular expressions, so I looked up the syntax and had at it. I ended up using analyze-string(), which, when used with groups, produces matching and unmatching strings, listed in order of occurence. Here's the result when matching that regular expression against the test data:


<analyze-string-result xmlns="http://www.w3.org/2005/xpath-functions">
   <non-match>x</non-match>
   <match>mul(<group nr="1">2</group>,<group nr="2">4</group>)</match>
   <non-match>%&mul[3,7]!@^do()_</non-match>
   <match>mul(<group nr="1">5</group>,<group nr="2">5</group>)</match>
   <non-match>+mul(32,64]thdon't()en(</non-match>
   <match>mul(<group nr="1">11</group>,<group nr="2">8</group>)</match>
   <match>mul(<group nr="1">8</group>,<group nr="2">5</group>)</match>
   <non-match>)wmxo_do()__</non-match>
   <match>mul(<group nr="1">10</group>,<group nr="2">2</group>)</match>
   <non-match>sxcer)</non-match>
</analyze-string-result>
							

Solution

I had this all in one template until I ended up using this same match function for part 2. Here's the guts of the match function:

See formatted solution code on GitHub: gar:accum-matches, line 109.

And here's the calling template:

See formatted solution code on GitHub: solution-part-1, line 125.

I added a bit more to the test data, particularly to test part 2.

Solution to the test data set

181

Solution to the actual data set

178538786

TIL a convenient use for the for-each-pair function.

Day 03, part 2

Discussion

Solution

For each do() line, it uses the same match function as part 1.

See formatted solution code on GitHub: gar:accum-matches, line 109.

The solution first tests if there's a line before a do or don't function since that defaults to a do line, then it runs the gar:accum-matches() function on each non-matching line whose preceding match is do(), summing it all up in the end.

See formatted solution code on GitHub: solution-part-2, line 138.

Solution to the test data set

53

Solution to the actual data set

102467299