Advent of Code F# — Day 3

ps. look out for all my oth­er solu­tions for Advent of Code chal­lenges here.


Day 3

See details of the chal­lenge here.

First, let’s cap­ture the input for today’s chal­lenge in a text file, say Day03Input.txt.

Then, let’s cre­ate a mod­ule to cap­ture the com­mon steps between both parts of the chal­lenge.

There’s real­ly not much to be said about the code snip­pet above, and the solu­tion for part 1 is also real­ly sim­ple.


Part 2

Now that you’ve help­ful­ly marked up their design doc­u­ments, it occurs to you
that tri­an­gles are spec­i­fied in groups of three ver­ti­cal­ly. Each set of three
num­bers in a col­umn spec­i­fies a tri­an­gle. Rows are unre­lat­ed.

For exam­ple, giv­en the fol­low­ing spec­i­fi­ca­tion, num­bers with the same hun­dreds
dig­it would be part of the same tri­an­gle:

101 301 501
102 302 502
103 303 503
201 401 601
202 402 602
203 403 603

In your puz­zle input, and instead read­ing by columns, how many of the list­ed
tri­an­gles are pos­si­ble?

You could, trans­pose the input (ie, a int[][]) so that you end up with some­thing along the lines of:

101  102  103  201  202  203 …

301  302  303  401  402  403 …

501  502  503  601  602  603 …

which will be eas­i­er to process, but it feels like more work than I’d like to do.

An alter­na­tive approach — the one I went with — is to use Seq.chunkBySize to group row indices into chunks of 3. For each chunk you can flat map (in F#, that’s Seq.collect) it to 3 tri­an­gles.

After that, it’s a case of apply­ing the isFil­ter func­tion we declared ear­li­er on the result­ing sequence.



Liked this post? Why not support me on Patreon and help me get rid of the ads!