Day 4’s challenge involved calculating “checksums” and decrypting data. Each line of the input contained an encrypted room name, a sector id and a checksum. Regular expressions were the obvious way to parse the input into a custom “Room” record type.

A few days practice means that I can at least use regular expressions fairly easily in F#, although it seems a shame that it takes several steps to parse out the matches from each group when other languages can often do this in a single line:

The next step was calculating the “checksum” for a room, which basically meant counting the frequency of letters in the room name, and picking out the five most common. The rules for sorting the letters were by frequency first and then alphabetical order. The countBy function is perfect for counting the characters in a string, and sorting by a tuple of frequency first (descending) and then character was idea. One thing that tripped me up is that F# has a String.concat which has a different signature from System.String.Concat

Part b of the problem required us to implement the Caesar cipher to decrypt room names. I made one function to decrypt a single character which is trivial apart from having to fight the F# compiler to let me do arithmetic on chars, and a function to decrypt a room name for which I used a pattern matching function in order to deal with the special case of dashes in the encrypted name

You can check out my full solution on GitHub. As usual my solution was nowhere near as concise as other people managed in different languages, but I’m fairly pleased with today’s solution, as I think it shows some of the benefits of good functional programming. We’re writing lots of small functions to solve individual pieces of the problem, which can be easily combined to solve the overall problem. Writing code like this means our solution is easier to understand, and also has built-in flexibility to help us answer other similar questions about our input data if we need to.

As always, let me know how you solved the problem or any ways you think my solution can be improved.

About Mark Heath

I'm a Microsoft MVP and software developer based in Southampton, England, currently working as a Software Architect for NICE Systems. I create courses for Pluralsight and am the author of several open source libraries. I currently specialize in architecting Azure based systems and audio programming. You can find me on: