DEV Community

Cover image for Tuning Trouble
Robert Mion
Robert Mion

Posted on

Tuning Trouble

Advent of Code 2022 Day 6

Part 1

  1. Could I use regex?
  2. Another way: substrings and Set()s
  3. My algorithm in JavaScript

Could I use regex?

Identify the first position where the four most recently received characters were all different

  • It seems I need one or more look-aheads
  • But I need each one to compare the character to three others
  • And I recall not being able to use back-references in look-aheads

After playing a bit with regexr.com and trying a few Google searches that skirted around a direct answer, I came up short.

Another way: substrings and Set()s

For a string like this:

mjqjpqmgbljsphdztnvjfqwrcgsmlb
Enter fullscreen mode Exit fullscreen mode

I could start from the first character:

*
mjqjpqmgbljsphdztnvjfqwrcgsmlb
Enter fullscreen mode Exit fullscreen mode

Capture a substring of the current and next three characters:

*+++
mjqjpqmgbljsphdztnvjfqwrcgsmlb
Enter fullscreen mode Exit fullscreen mode

Split into an array and create a Set():

{ 'm', 'j', 'q' }
Enter fullscreen mode Exit fullscreen mode

And check whether the size of the Set() is equal to 4.

If it is, I found my match!

Otherwise, I'll move to the next character and try again.

My algorithm in JavaScript

let i = 0
let answer = null
while (answer == null) {
  answer = new Set(
    input.slice(i, i + 4).split('')
  ).size == length ? i + 4 : null
  i++
}
return answer
Enter fullscreen mode Exit fullscreen mode

Part 2

  1. Just add 10? Really?
  2. My algorithm in JavaScript
  3. My combined algorithm in JavaScript

Just add 10? Really?

Does this hint at an optimization opportunity or performance test?

I'm hopeful my algorithm will still finish quickly.

My algorithm in JavaScript

let i = 0
let answer = null
while (answer == null) {
  answer = new Set(
    input.slice(i, i + 14).split('')
  ).size == length ? i + 14 : null
  i++
}
return answer
Enter fullscreen mode Exit fullscreen mode

That is nearly identical to Part 1's algorithm, with only the character count changed.

I'm compelled to turn it into a reusable function.

My combined algorithm in JavaScript

(count) => {
  let i = 0
  let answer = null
  while (answer == null) {
    answer = new Set(
      input.slice(i, i + count).split('')
    ).size == length ? i + count : null
    i++
  }
  return answer
}
Enter fullscreen mode Exit fullscreen mode

I did it!!

  • I solved both parts!
  • I wrote a subroutine that accepts any number of distinct characters!

This puzzle referenced several Assembly-themed puzzles from earlier years.

That gave me goosebumps, because I never really enjoyed those puzzles: too difficult to debug.

Thankfully, that was all just for fun.

This puzzle ended up being relatively easy, even without any regex!

Top comments (0)