Advent of Code: Day 2 Solution

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:

And the instructions look like this:

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

  1. Set Keypad = a grid of X and Y coordinates, with the keypad value (0,0 = 7, 2,2=3)
  2. Set CurrentX=1 (second column)
  3. Set CurrentY=1 (second row)
  4. Set Code=nothing
  5. For each line in instructions
    1. For each letter in instructions
    2. Set PreviousX=CurrentX
    3. Set PreviousY=CurrentY
    4. If U, CurrentY=CurrentY+1
    5. If D, CurrentY=CurrentY-1
    6. If L, CurrentX=CurrentX-1
    7. If R, CurrentX=CurrentX+1
    8. If CurrentX,CurrentY is not a valid point on Keypad
      1. Set CurrentX=PreviousX
      2. Set CurrentY=PreviousY
    9. End if
    10. Append Keypad.Value at CurrentX,CurrentY to Code
  6. Return Code

Day 2, part 2

The keypad is not a standard 3×3 grid, as expected. It actually looks like:

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

Leave a Reply

Your email address will not be published. Required fields are marked *