Advent of Code 2022: Day 6

by Michael Welborn on 2023-01-16

We're back from the holidays and have a simple puzzle to ease ourselves into problem solving. If you haven't already, take a look at the prep work we did on day 0, and view the puzzle description on AoC.

Our puzzle input is a simple, single-line data stream.

mjqjpqmgbljsphdztnvjfqwrcgsmlb

Which is easy enough to hold onto as a str.

from solver import Solver


class TuningTrouble(Solver):
    data_stream: str

    def parse_input(self) -> None:
        self.data_stream = self.input_text.strip()

Part One

In our data stream, we're looking for a start-of-packet marker. This is signified by 4 characters that are all different. The desired output is the index of the last character in the marker.

To solve this, we'll need a sliding window of size four along the data stream. If all four characters in the window are different, we've found the marker.

more-itertools can fill both of these needs with windowed and all_unique, respectively. We'll just need to keep track of the index of the last character in the window with enumerate, starting with 4.

Also, let's parameterize the length of the window (and thereby the length of the marker) just for fun. Who knows, we might need it later.

from more_itertools import all_unique, windowed
from solver import Solver


class TuningTrouble(Solver):
    ...

    def marker_index(self, length: int) -> int:
        windows = windowed(self.data_stream, length)
        for index, window in enumerate(windows, start=length):
            if all_unique(window):
                return index

    def solve_part_one(self) -> int:
        return self.marker_index(length=4)

That takes care of part one. Testing it with the sample input produces the correct answer 7.

Part Two

The desired output for part two is the same as part one, except the marker is 14 distinct characters. Well what do you know! We've already got that ready to go.

class TuningTrouble(Solver):
    ...

    def solve_part_two(self) -> int:
        return self.marker_index(length=14)

And that solves part two. Testing it with the sample input produces the correct answer 19.

A nice, easy puzzle with the tools we have at our disposal. But my puzzle sense is tingling. I think the next one will be a bit more involved.

You can try this solution in your browser with Pyodide.