AOC 2022 — Day 6

Matt E.
4 min readJan 26, 2023

In this article, I’ll present my solution for the day 6 of the Advent of Code 2022

You can find here my solutions for the previous challenges : Day 1, Day 2, Day 3, Day 4, Day 5

https://adventofcode.com/2022/day/6

The expedition is ready to make their way toward the star fruit grove. One of the elves gives you a handheld device. This device has many fancy features, but your first focus is the communication system.

As you’re experienced with this kind of system, the elf convinced the others that they could give you the broken device.

To fix the communication system, you need to implement a subroutine able to decrypt the datastream.

Part 1

For the first part of this challenge, the goal is to identify that start-of-packet marker.

In the protocol used by the elves, the start-of-packet marker is indicated by a sequence of four characters that are all different.

Input

The input you receive is a simple string. If we take the following example :

mjqjpqmgbljsphdztnvjfqwrcgsmlb
  • The first 4 characters are mjqj, the j is there twice so that’s not the marker
  • The next 4 are jqjp, j is still there twice
  • Then it’s qjpq, q is present twice, so that’s not the marker either
  • Then it’s jpqm, all characters are different so we found our marker

The goal of this exercise is to find the number of characters you need to process before finding the marker. Here it’s 7 ( mjqjpqm).

Solution

To solve this exercise, I’ll look at the characters 4 by 4, going forward from 1 character each time.

To check if some character appears twice, I will sort the array. This allows us to put all identical characters next to each other.

Then I only need to check that every character is different from the one right after it.

It will give us something like this :

For i = 4; index < input.length; i += 1:
Array = sub-array of input, from index i - 4 to index i

Sort Array

If Array[0] !== Array[1] and Array[1] !== Array[2] and Array[2] !== Array[3]…

--

--

Matt E.

Software engineer at Achiev & Jounco. Passionate about programming and entrepreneurship