Advent of Code 2017 Day 5
Part 1
- This seems very familiar...
- Writing my working algorithm
This seems very familiar...
- Jumps? Been there, done that!
- Terminate when outside the list boundary? Ditto!
- Increment the current instruction's value by 1 before jumping? That's a fun twist!
Writing my working algorithm
Split the input at each newline character into an array of strings
Coerce each string to a number
Set pointer to 0
Set steps to 0
Do as long as pointer references an index within the bounds of the array of jumps
Save the number of the current jump instruction
Increment that number by 1
Update pointer to the sum of pointer and the prior number of the current jump instruction
Increment steps by 1
Return steps
In JavaScript, I wrote this concise program:
let jumps = input.split('\n').map(Number)
const part1 = () => {
let pointer = 0, steps = 0
while (pointer >= 0 && pointer < jumps.length) {
pointer += jumps[pointer]++
steps++
}
return steps
}
Running on both the example input and my puzzle input generated the expected and correct answers!
Part 2
- The twist is...not that difficult
- Updating my working algorithm
The twist is...not that difficult
It seems like I'll now need a condition when updating the value at pointer before updating pointer.
Updating my working algorithm
Split the input at each newline character into an array of strings
Coerce each string to a number
Set pointer to 0
Set steps to 0
Do as long as pointer references an index within the bounds of the array of jumps
Save the number of the current jump instruction
If that number is 3 or more
Decrement that number by 1
Else
Increment that number by 1
Update pointer to the sum of pointer and the prior number of the current jump instruction
Increment steps by 1
Return steps
Running on the example input generated the wrong answer!
What's happening?
Oh...I see:
- I mistakenly put my statement that generated the list of jumps outside each of my
part1
andpart2
functions - So, my
part2
function was operating on a pre-processed list of jumps - Silly me...but also not the first time that's happened
After moving that statement into each function and re-running:
- Running on both the example input and my puzzle input generated the expected and correct answers!
In JavaScript, I wrote this nearly identical, concise program:
const part2 = () => {
let jumps = input.split('\n').map(Number)
let pointer = 0, steps = 0
while (pointer >= 0 && pointer < jumps.length) {
pointer += jumps[pointer] >= 3 ? jumps[pointer]-- : jumps[pointer]++
steps++
}
return steps
}
I did it!!
- I solved both parts!
- I implemented my Part 1 algorithm exactly as outlined in pseudocode in this article, which made writing it feel super easy!
- I was surprisingly disappointed - and perhaps grateful? - by the lack of difficulty of Part 2 relative to Part 1!
- I'm now two stars away from matching my personal best star score for a given year!
Top comments (0)