Advent of Code 2022 - Day 6 Javascript Solution

By Henri Parviainen

Advent of Code Cover image for day 6 in 2022

It's time for the daily Advent of Code solution update for day 6! Today's puzzle felt like a breeze compared to yesterdays parsing and heres my take on it using Javascript.

Disclaimer

This solution is not the fastest implementation nor is it claiming to be the best way to solve the problem. There are many ways to solve it and this is just how I did it with Javascript. By sharing I hope it can help someone who is struggling to find a solution to the puzzle.

Parts 1 & 2

For today's puzzle, I just copied the input straight to the code since it was just a string. I have shortened it here to make it look a bit cleaner.

let input = "bhbbtooirewssqqpoollhursqqixcvoo";

// Helpers

const getLastCharacters = (amount, characters) => {
  characters = characters.slice(characters.length - amount, characters.length);
  let lastChars = [];
  for (let character of characters) {
    lastChars.push(character);
  }
  return lastChars;
};

// Part 1 & Part 2

const findStartPoints = (markerLength, input) => {
  let letters = [];
  let counter = 0;
  for (const letter of input) {
    counter++;
    letters.push(letter);
    let lastCharacters = getLastCharacters(markerLength, letters);
    let isUnique = [...new Set(lastCharacters)];
    if (isUnique.length == markerLength && !isUnique.includes(undefined)) {
      console.log(counter);
      return;
    }
  }
};

findStartPoints(4, input);
findStartPoints(14, input);

There you go! Day 6 is done, and on to the next one..

SHARE