Advent of Code 2022: Day 6
A TypeScript solution for the Advent of Code 2022, Day 6 puzzle: using the Set object for uniqueness checks.
Today’s puzzle asks us to search for the first (ending) position in a large string where a substring of a certain length contains all unique characters.
The puzzle input data looks something like this.
mjqjpqmgbljsphdztnvjfqwrcgsmlb
We can define a search()
function quite simply by taking advantage of two key JavaScript features:
String.prototype.slice()
for getting a substring of characters within a start and end position- The
Set
object, for easily checking if a set of characters is unique
const search = (str: string, len: number) => { for (let ii = len; ii < str.length; ii++) { const substring = str.slice(ii - len, ii); if (new Set(substring).size === len) { return ii; } } }
One might be tempted to write a long series of boolean conditionals for part 1, since we only need to check uniqueness between 4 characters. However, part 2 asks us for a unique substring length of 14, which would make writing a bunch of conditionals untenable. By using a Set
, which is like a hash table, it simplifies the uniqueness check and makes it dynamically scalable to larger substrings.
So we can just call our search function with two different len
parameters, 4
and 14
for part 1 and part 2 respectively.
const part1 = search(puzzleInput, 4); const part2 = search(puzzleInput, 14);
Final Solution
const search = (str: string, len: number) => { for (let ii = len; ii < str.length; ii++) { const substring = str.slice(ii - len, ii); if (new Set(substring).size === len) { return ii; } } } const part1 = search(puzzleInput, 4); const part2 = search(puzzleInput, 14); console.log("Part 1:", part1); console.log("Part 2:", part2);
Part 1: 1210 Part 2: 3476