Advent of Code 2022 — Day 2 [Python]
Today I will be solving the second day of the advent of code calendar with you. I found this one very amusing since it is a concept everyone is familiar with, rock, paper, and scissors. In this case with a small twist but alas something I recognized.
Here is the task: https://adventofcode.com/2022/day/2
Day 2 tasks you with finding out what score you would have if you added up your wins and losses, your input, according to a table we got from the task.
Let’s start…
Part 1
In the first part of the days task we assume the input we got from an elf was the hands we and out oppoenets threw:
The first one, C, would be the opponent and the second one, X, the player aka. us. And so on for each line. Then we are supposed to calculate what our final score would be considering the table of scores we get from the task. Let’s start coding this:
First of all we need to get the data from the input.
Here I get the input data from the file I called “day2.in” where I copied my input data into.
Now that I have the input data in a list I make a quick dictionary to remember the values of the symbols in the input:
In this way it’s easier to later get the values of the different letters when we are summing up the final score.
Also make a fullscore variable where we will be counting the final result:
Now we have everything set up and ready we are going to loop through the values in the input data list, with a for-loop:
In this for-loop I am going to make a variable to keep track for each sum and getting the player and opponent values out of the list and the dictionary.
Then we need to look through if the player won (+6) the game or it was a draw (+3), if the player lost it won’t get any points so we don’t need to make an if-statement for this. Here 2,1,3 correspond to the letters in the dictionary.
After we are done with this we are almost done with part 1 of the task. Now the only thing left is to sum everything up and print out the final answer.
My answer for part 1 was: (printed in terminal)
Part 2
For part 2 of day 2 we only need to add one small part of code and we will get the answer.
For part 2 we got intell from the elf that the strategy we got before (the input) was meant to tell us if we should win, loose or draw, and we interpreted it wrong. Now we are gonna interpret it right and see what our final score will be now.
This will go between the getting values, setting variables part and the if-statements part.
Here there will be a lot of if-statements to make sure the player wins, losses or draws. Put the players value (me) to either the same as for the opponent (draw), to the value that will beat the opponent (win) or to the value that will lose to the opponent (lose). Here are the if-statements:
This is all you need to change in the code from part 1 to get the answer to part 2.
My answer for part 2 was: (printed out in the terminal)
Hope this helped you and you beat day 2 of the code advent calendar! Happy coding!