Advent of Code F# — Day 2

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

 

Day 2

See details of the chal­lenge here.

Let’s start by cap­tur­ing the mod­el and input data in a mod­ule. Since I’m armed with the hind­sight of hav­ing seen both parts of today’s chal­lenge I’ve refac­tored the com­mon log­ic into a solve func­tion:

  • there’s a key­pad
  • after each move (U, D, L or R) we need to check if the new posi­tion is a but­ton, and ignore it if not
  • cap­ture the but­ton we fin­ished at at the end of each line

The inter­est­ing thing here is the no doubt the solve func­tion.

After we parse the input string we end up with a Direc­tion[][], which we’ll scan over to get the posi­tions on the key­pad we end up at after each line of the input.

How­ev­er, Array.scan includes the ini­tial val­ue we passed in, which we can solve with Seq.skip 1.

The rest, is just a case of stich­ing togeth­er the actu­al val­ues from the key­pad.

Now that we have the core flow of the solu­tion in place, let’s fill in the bits we need to solve part 1:

 

Part 2

You final­ly arrive at the bath­room (it’s a sev­er­al minute walk from the lob­by so vis­i­tors can behold the many fan­cy con­fer­ence rooms and water cool­ers on this floor) and go to punch in the code. Much to your bladder’s dis­may, the key­pad is not at all like you imag­ined it. Instead, you are con­front­ed with the result of hun­dreds of man-hours of bath­room-key­pad-design meet­ings:

    1
  2 3 4
5 6 7 8 9
  A B C
    D

You still start at “5” and stop when you’re at an edge, but giv­en the same instruc­tions as above, the out­come is very dif­fer­ent:

  • You start at “5” and don’t move at all (up and left are both edges), end­ing at 5.
  • Con­tin­u­ing from “5”, you move right twice and down three times (through “6”, “7”, “B”, “D”, “D”), end­ing at D.
  • Then, from “D”, you move five more times (through “D”, “B”, “C”, “C”, “B”), end­ing at B.
  • Final­ly, after five more moves, you end at 3.

So, giv­en the actu­al key­pad lay­out, the code would be 5DB3.

Using the same instruc­tions in your puz­zle input, what is the cor­rect bath­room code?

We can present the key­pad in part 2 as a Option<char>[][].

The only oth­er dif­fer­ence to part 1 is that we need to deal with the emp­ty spaces on the key­pad, here­by rep­re­sent­ed as None.

With these two pieces, part 2 is pret­ty straight for­ward too.

 

Links