Advent of Code 2022 Day 6
Part 1
- Could I use
regex
? - Another way: substrings and
Set()
s - 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
I could start from the first character:
*
mjqjpqmgbljsphdztnvjfqwrcgsmlb
Capture a substring of the current and next three characters:
*+++
mjqjpqmgbljsphdztnvjfqwrcgsmlb
Split into an array and create a Set()
:
{ 'm', 'j', 'q' }
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
Part 2
- Just add 10? Really?
- My algorithm in JavaScript
- 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
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
}
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)