Advent of Code F# – Day 8

The source code for this post (both Part 1 and Part 2) is avail­able here and you can click here to see my solu­tions for the oth­er Advent of Code chal­lenges.

Descrip­tion for today’s chal­lenge is here.


The input for Day 8 looks like the fol­low­ing:







bear­ing in mind that the lead­ing and trail­ing dou­ble quotes (“) are also part of the input and needs to be dealt with.

Since there are so many escape char­ac­ters in the input, I decid­ed it would be eas­i­er to put it in a text file:


and for each line, we will:

  1. trim the lead­ing and trail­ing ”
  2. turn the string into a list of chars
  3. recur­sive­ly process the list, and unescaped any escaped chars (e.g. \\, \”, \x39):


What’s going on with this:

    | IsEscaped (char, rest) -> …

well, that’s our super secret par­tial active pat­tern that is respon­si­ble for unescap­ing escaped char­ac­ters:


Cou­ple of things to note from this:

  • it’s tak­ing the entire remain­der of the char list as input
  • if the list is lead­ing with \\ or \” then the unescaped \ or ” is returned along­side the rest of the list
  • in the case of \x66 for exam­ple, we can take advan­tage of int and char con­ver­sions:
    • int “0x66” will turn the hex val­ue 66 into the cor­re­spond­ing inte­ger val­ue 102
    • char 102 will return the char with the cor­re­spond­ing ASCII val­ue — ‘f’

Final­ly, we just need to com­pare the total length of the raw input and the unescaped chars:


Part 2

Here we need to do the reverse of what we did in Part 1, but the approach is sim­i­lar — process each char, and escape \ and ” when­ev­er we see them:


and then just com­pare the length of the orig­i­nal and the encod­ed ver­sion to answer the chal­lenge: