Today’s Advent of Code puzzle required us to work through a series of instructions. Each instruction was simply the offset of the next instruction to jump to, but we also needed to modify the offsets as we went.

My solution for part 1 was fairly simple. Read the instructions into an array of integers, and loop through them, executing each one until the exit condition was met:

``````function solve(input, part) {
const offsets = input.map(Number)
return countStepsUntilExit(offsets);
}

function countStepsUntilExit(offsets) {
let currentIndex = 0;
let steps = 0
while(currentIndex >= 0 && currentIndex < offsets.length) {
let skip = offsets[currentIndex];
offsets[currentIndex] += 1;
currentIndex+=skip;
steps++;
}
return steps;
}
``````

For part 2, the rule to update offsets changed, but we can modify `countStepsUntilExit` to be a higher order function capable of solving both parts with minimal code changes:

``````function solve(input, part) {
const offsets = input.map(Number)
return countStepsUntilExit(offsets, part === 1 ? () => 1 : n => (n>=3)?-1:1);
}

function countStepsUntilExit(offsets, updateOffset) {
let currentIndex = 0;
let steps = 0
while(currentIndex >= 0 && currentIndex < offsets.length) {
let skip = offsets[currentIndex];
offsets[currentIndex] += updateOffset(skip);
currentIndex+=skip;
steps++;
}
return steps;
}
``````