Advent of Code F# – Day 24

Yan Cui

I help clients go faster for less using serverless technologies.

ps. look out for all my other solutions for Advent of Code challenges here.

 

Day 24

See details of the challenge here.

Today’s challenge is a mix of Breadth-First Search (or Level Order Tree Traversal) and the Travelling Salesman Problem.

First, let’s parse the input file into a 2D array to make it easier for us to work with.

My first attempt at solving this challenge with the same BSF approach that has been so useful in this year’s AOC challenges proved unsuccessful. Unlike previous challenges, today’s problem can involve backtracking so we can’t rely on a naive cache of positions we have passed through thus far.

However, we can still use BSF to find out the shortest distance between any two numbered nodes.

From here, we can build up a dictionary of the distance between every pair of numbered nodes and turn this BSF problem into a Travelling Salesman Problem and find the path through all the numbered nodes with the lowest total distance.

Now we can solve part 1 of the challenge with a simple recursive function.

This solution ran in 109ms on my laptop, including the time to build up the distances between pairs of nodes.

 

Part 2

Of course, if you leave the cleaning robot somewhere weird, someone is bound to notice.

What is the fewest number of steps required to start at 0, visit every non-0 number marked on the map at least once, and then return to 0?

A slight twist on part 1, but we can use the same approach as before but simply stipulate that when all numbered nodes have been traversed we also take into account the distance from the last node back to number 0.

This ran in 113ms on my laptop, including the time to build up the distance between pairs of nodes (or, 14ms if reusing the existing pairDistances)

 

Links


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.