DEV Community

Nicky Meuleman
Nicky Meuleman

Posted on • Originally published at nickymeuleman.netlify.app

Advent of Code 2022 Day 6

Day 6: Tuning Trouble

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

TL;DR: my solution in Rust

Today we get a communication device from an elf.

A stream of characters get sent to the device.
Your input is the stream it receives.

An example input looks like this:

mjqjpqmgbljsphdztnvjfqwrcgsmlb
Enter fullscreen mode Exit fullscreen mode

Part 1

The start of a packet-marker is the first sequence of 4 characters that are all different.

The question asks to find how many characters had to be checked when we detect the first marker.

I looped over sliding windows of size 4.
For each window, I check if all characters in it are unique.

To check if all characters in a window are unique,
I loop through the window and check if the character at that point exists in the window so far.

window
    .iter()
    .enumerate()
    .all(|(idx, c)| !window[..idx].contains(c))
Enter fullscreen mode Exit fullscreen mode

I could have also checked for uniqueness differently:
If a set of a window has the same length as the window itself, all items in that window are unique.

window.iter().collect::<HashSet<char>>().len() == window.len()

The first window that passes that check is the first marker.

The index of that window is the beginning of that 4 character marker.

Add 4 to that index to find how many characters have been received up to that point.

pub fn part_1() -> usize {
    let input = std::fs::read_to_string("src/day06.txt").unwrap();

    input.as_bytes()
        .windows(4)
        .position(|window| {
            window
                .iter()
                .enumerate()
                .all(|(idx, c)| !window[..idx].contains(c))
        })
        .unwrap()
        + 4
}
Enter fullscreen mode Exit fullscreen mode

Part 2

The start of a message is the first sequence of 14 characters that are all different.

The question asks to find how many characters had to be checked when we detect the first message.

This code is identical to part1, but that constant of 4 is now 14.

pub fn part_2() -> usize {
    let input = std::fs::read_to_string("src/day06.txt").unwrap();

    input.as_bytes()
        .windows(14)
        .position(|window| {
            window
                .iter()
                .enumerate()
                .all(|(idx, c)| !window[..idx].contains(c))
        })
        .unwrap()
        + 14
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)