Advent of Code: Day 12 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 12, part 1

I wasn’t sure whether I’d be able to continue after Day 11. I hit a similar wall last year, although I think I may be able to solve some of the later puzzles from last year.

Simplified problem: Using instructions written in a similar style to Assembler, calculate the value of register a once the instructions have been completed.

There are 4 registers: a, b, c, and d. All registers are initialised with a value of 0. There are four instructions:

  • cpy x y copies x (either an integer or the value of a register) into register y.
  • inc x increases the value of register x by one.
  • dec x decreases the value of register x by one.
  • jnz x y jumps to an instruction y away (positive means forward; negative means backward), but only if x is not zero.

After completing the instructions in input, what is the value in register a?

Solution

  1. Set Instructions=(your input)
  2. Set index=0 (this is the instruction index)
  3. While index < number of Instructions
    1. Set parts = instructions[index], split on the space character
    2. Set instruction=parts[0]
    3. If instruction=”cpy”
      1. If parts[1] is a register
        1. Set value=register value
      2. Else
        1. Set value=parts[1]
      3. End If
      4. Set register[parts[2]]=value
    4. Else if instruction=”inc”
      1. register[parts[1]]=value+1
    5. Else if instruction=”dec”
      1. register[parts[1]]=value-1
    6. Else (instruction=”jnz”)
      1. If parts[1] is a register
        1. Set registervalue=registers[parts[1]]
      2. Else (value is a literal number)
        1. Set registervalue=parts[1]
      3. End If
      4. If registervalue is not equal to 0
        1. Set index=index+parts[2]
      5. End If
    7. End If
    8. If instruction is not “jnz
      1. Set index=index+1
    9. End If
  4. End While
  5. Return value of register[a]

Day 12, part 2

Using the same rules and input as in Part 1, what the value of register a if register c is initialised to 1?

Solution

Perform the same steps as in Part 1, setting register c to 1 instead of 0.

This process can take quite some time.

You can find the full solution on Github

Leave a Reply

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