
Day 4 challenge of the mighty Advent of Code 2024
Created at:
Last updated:
Welcome to day 4 of Advent of Code. Before we start talking about the today's problem, please read the whole story here. Today, we are presented with a bunch of scratchcards. Each scratchcard has its number, a list of winning numbers and a list of numbers we scratched. We are asked to find how many numbers are winning and calculate the number of points we gain with each scratchcard by starting with one point for one match and doubling the points with each next matching number doubles the amount of points, so for two matching numbers the amount of points is 2 and for 3 matches its 4. Then to get the final answer we need to sum up all the points from every scratchcard.
Let's analyze the test data:
Here we can see three parts building each game data (from left to right):
We are going to start by creating the new directory in or project's root directory.
We also create new file inside the folder, which will be our main entry for the code for this puzzle.
We can also put the test input data.
To parse the cards data from the text, we need to break down the task into few steps:
And when we run this piece of code we get:
Technically we do not need the , but I decided to add it anyway. Other than that we have all the data in an easy to use format now, so lets commit what we made.
This should be a fairly simple task. We simply need to loop through our numbers and check it they are present in the list of winning numbers. we return the count of matching numbers as a result.
The code gives us an array like this:
This matches our analysis we did in the introduction. we can now commit the changes and move forward.
If we think about how we are calculating the points we can see that it is a to the power of matches - 1 or in case of no matches we return 0.
Here are the results:
And this is still matching what we have calculated manually. We can also calculate the sum of the points.
This gives us the final result which confirms that our calculations are correct.
Now we can save our work.
The great moment has come, it is time to run our code on the real input data. As we did in all our previous challenges, we will use function. We replace from being the hard-coded test data to be read from file.
Running the whole code we have prints this message in the terminal:
Now we can submit the result. Are we correct?
YES!
We can now commit the final version of our little program.
Congratulations to all of you who solved the puzzle together with me. Now its time to beat the part two. See you all in Day 4, part 2!
Please Sign in to leave a comment.