Day 20’s puzzle at Advent of Code was in one sense very simple, but if you weren’t careful, you’d create a solution that took ages. In today’s video, I explain how I initially came up with a very slow solution, and then showed some ways that dramatically speeded it up.

Here’s my first C# version, that uses a naive algorithm to calculate the presents for each house. Even trying to optimize by excluding houses without multiple prime factors from the search space didn’t really make up for how slow the present counting was.

So in my F# version, I used a more intelligent approach, getting all the factors of the house number in order to work out which elf visited. The factors function is based on one by Jeff on the Advent of Code subreddit. I left in my optimization of only testing likely houses from C#. Overall this factors optimization sped up the calculation of part b’s answer from 18 minutes down to under a second!

But what’s interesting is that there is a much simpler way to solve this problem which also happens to perform very fast. Annoyingly it’s the first solution I turned to, but then abandoned quickly. Basically, have an array of presents for each house, and then for each elf, update the total for all the houses they visit. This works almost as fast as the optimized F# solution, and could be optimised further if necessary by stopping as soon as any house has more than the target number of presents, and reducing the number of houses calculated as it is overkill to try so many. But here’s this solution in C#, and well done to r_sreeram who used it to get first place on the leaderboard.

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: