This year, I’m posting my solutions to the puzzles in the Advent of Code. Each post will consist of pseudocode, with a link to the actual code I used to solve the puzzle on Github.
And now, on with the solution:
Day 2, part 1
Simplified problem: You need to determine the code to a keypad. The keypad looks like this:
1 2 3 |
1 2 3 4 5 6 7 8 9 |
And the instructions look like this:
1 2 3 4 |
ULL RRDDD LURDL UUUUD |
The instructions are composed of single movements: Up, Down, Left and Right. If there is no button at the destination position (i.e. move Up from the 2 button), do not move (i.e. remain on the 2 button). The code is the last number reached at the end of each line.
Starting at the number 5, the first number in this code would be 1: Move Up to 2, move Left to 1, then remain on 1 as there is no button to the left of the 1 button. The next set of instructions is followed from the last point (i.e. 1).
Solution
- Set Keypad = a grid of X and Y coordinates, with the keypad value (0,0 = 7, 2,2=3)
- Set CurrentX=1 (second column)
- Set CurrentY=1 (second row)
- Set Code=nothing
- For each line in instructions
- For each letter in instructions
- Set PreviousX=CurrentX
- Set PreviousY=CurrentY
- If U, CurrentY=CurrentY+1
- If D, CurrentY=CurrentY-1
- If L, CurrentX=CurrentX-1
- If R, CurrentX=CurrentX+1
- If CurrentX,CurrentY is not a valid point on Keypad
- Set CurrentX=PreviousX
- Set CurrentY=PreviousY
- End if
- Append Keypad.Value at CurrentX,CurrentY to Code
- Return Code
Day 2, part 2
The keypad is not a standard 3×3 grid, as expected. It actually looks like:
1 2 3 4 5 |
1 2 3 4 5 6 7 8 9 A B C D |
Use the same instructions to determine the code for the new keypad.
Solution
Uses the same code as above, but generates a different keypad grid.
You can find the full solution on GitHub