Hello everyone, it’s time for your Advent of Code 2021 Day 10 cruise log. I don’t quite know what to say about this one. I know that in yesterday’s post I was hoping for a more challenging day but didn’t get it so long as it doesn’t go too crazy. Let’s see whether the gods of coding granted my wish.
As I read through the problem statement I realised I knew this problem. I solved it on Hackerrank a few years ago. Of course, this was a different flavour but the core was the same. Going through strings with opening and closing sequences and determining illegal sequences.
If you’ve got an expected closing pattern for each opening pattern, it’s safe to assume a map will help you. A map where the key would be the opener and the value would be the expected closer. Pretty straightforward. For each input line, we would need to return find the first illegal pattern. Even though it is essential for a clean solution, a map is not enough.
As it turns out, you need another data structure. Now that would be a data structure that would allow you to have some sort of pile. A pile where you would stack the openers so that when you get a closer you can check if it matches the opener with that map. Fortunately, in most languages, there is such data structure, in Java and C# it’s the generic
Now that we have our data structures, life becomes easy. We loop through the elements and for each of them if the pattern is an opener, we push it on the opener stack. However, if it is a closer and matches the latest opener then we pop that opener, otherwise, we got our illegal. From there it’s a piece of cake. Following that implementation, the second part is pretty straightforward. You can copy your illegal detection and adjust it to complete the expected legal entry. Super easy, barely an inconvenience. One star, two stars, twenty stars.
Considering how easy days 9 and 10 have been to me, I can’t help but wonder. Was there an easy, obvious, brute-force-free solution for day 8? I must have missed something. I’ll probably look up some people solutions on Reddit to see others’ code. This might teach me a thing or two.
Thank you for reading my Advent of Code 2021 Day 10 log, I will see you tomorrow. As usual, I will push the code to my repo for this year on Github. Feel free to check out my Day 9 log right here.
Photo by Suzy Hazelwood from Pexels