Day 8, part 1
Day 8 challenge of the mighty Advent of Code 2024
Created at:
Last updated:
Table of Contents
Introduction
Today's challenge is about finding the path on a map which looks something like this:
It is build out of two parts: the instructions and nodes. Starting with , you need to look up the next element based on the next left/right instruction in your input. In this example, start with and go right () by choosing the right element of , . Then, means to choose the left element of , . As the result we have to count how many steps we had to take to make it from to
Solution
To get what we need, we can divide our problem into steps:
- Parse input data - without this it is hard to process it further
- Take the node as a starting point and based on the instructions move through the nodes until you get to . Seems to be pretty straight forward, doesn't it?
Parse input data
So first we are taking the test data in a form of text, and we want to get something more useful out of it. From the first line we extract the instructions into an array and the rest is our nodes' data which we transform into node s. Each has its name and indicates which node would we get going left and which going right. These properties are named and to match the instruction names to make it easier to move through the data later.
Let's run this and see if what we get is what we were looking for.
This is exactly what we expected, so we can commit these changes before moving forward.
Crawl the desert
Now when we have our data in easily digestible form, we can start crawling through the nodes until we get to the final destination. Basically this whole process can be split into steps:
- We get the current node object based on its name
- We check if we didn't get to the end of the instructions - if so, we start form the begging.
- We find the next node based on the current instruction and the current node.
- We keep counting steps during this process. The code which does that looks like this:
Looking at the test data and solving the puzzle by hand, we can see that the resulting amount of steps here is . So lets run this piece of code and see if our assumption is correct.
Looks like we did it! We can save our progress.
Final result
This is the time to test our code in battle. Once again we will use the function, to get the real input data, which we copy from the Advent of Code website and we put the data inside file.
Now we run the code and we can see in the terminal:
If we submit the answer we can see:
Great! It looks like we are right once again!
We can save the final result.
And I hope to see you in 16. day 8, part 2!