If you missed any previous days, click here for all my content about that: Advent of Code, if you want to know why you should participate and try to code the solution for yourself, click here: Advent Of Code 2022 – 7 Reasons why you should participate. If you’re here to see the solution of Day 6, continue reading 😉
I will upload all of my solutions there – in the form of Python (or Scala alternatives) notebooks. You have to use your own input for the “input.txt” since everyone gets their own and everyone needs to provide a different solution based on their input.
Day 6 Puzzle
Okay, for everyone who has participated or seen the solutions to the last few days – or even just the puzzle for yesterday: what the heck was this today? 😀 Prepare for super short blog post.
On day 6 of Advent of Code, we had to fix the communication device the elves gave us. Which sounds complicated until you read the concrete task at the end.
We had to read in a line and find the first 4 distinct characters in a row. We then get the solution from the index of the end of this 4-character-section. Yeah, that’s it. Here’s the code.
with open('example.txt', 'r') as f: line = f.readline().strip() for i in range(len(line)): if len(set(line[i:i+4]))==4: print(i+4) break
- iterate over the length of the line
- at each spot check the next 4 characters (
line[i:i+4], if you don’t know this syntax search for “list slicing”)
- convert to a set because a set doesn’t have duplicates
- if the set is still length 4, there are no duplicates in this part of the string and we found our solution, which is the current index + 4 to return the end of this 4-character sequence
Okay, here we had to the same, but for 14 distinct characters. So just replace every 4 with 14 in the above code:
with open('example.txt', 'r') as f: line = f.readline().strip() for i in range(len(line)): if len(set(line[i:i+14]))==14: print(i+14) break
What the heck. You know what, I’ll take it, I still have a Vlogmas video to edit today *shrug*.