Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Advent of Code 2024 - Day 17

2024/elixir/livebooks/day17.livemd

Advent of Code 2024 - Day 17

Mix.install([
  {:kino_aoc, "~> 0.1"},
  {:flow, "~> 1.2"}
])

Introduction

— Day 17: Chronospatial Computer —

The Historians push the button on their strange device, but this time, you all just feel like you’re falling.

“Situation critical”, the device announces in a familiar voice. “Bootstrapping process failed. Initializing debugger….”

The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you.

This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren’t limited to 3 bits and can instead hold any integer.

The computer knows eight instructions, each identified by a 3-bit number (called the instruction’s opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand.

A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction’s opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts.

So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt.

There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows:

  • Combo operands 0 through 3 represent literal values 0 through 3.
  • Combo operand 4 represents the value of register A.
  • Combo operand 5 represents the value of register B.
  • Combo operand 6 represents the value of register C.
  • Combo operand 7 is reserved and will not appear in valid programs.

The eight instructions are as follows:

The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction’s combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register.

The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction’s literal operand, then stores the result in register B.

The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register.

The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction.

The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.)

The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.)

The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.)

The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.)

Here are some examples of instruction operation:

  • If register C contains 9, the program 2,6 would set register B to 1.
  • If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2.
  • If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A.
  • If register B contains 29, the program 1,7 would set register B to 26.
  • If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354.

The Historians’ strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example:

Register A: 729
Register B: 0
Register C: 0

Program: 0,1,5,4,3,0

Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0.

Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?

— Part Two —

Digging deeper in the device’s manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You’ll need to find a new value to which you can initialize register A so that the program’s output instructions produce an exact copy of the program itself.

For example:

Register A: 2024
Register B: 0
Register C: 0

Program: 0,3,5,4,3,0

This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.)

What is the lowest positive initial value for register A that causes the program to output a copy of itself?

Puzzle

{:ok, puzzle_input} =
  KinoAOC.download_puzzle("2024", "17", System.fetch_env!("LB_AOC_SESSION"))
IO.puts(puzzle_input)

Parser

Code - Parser

defmodule Parser do
  def parse(input) do
    [registers, program] =
      input
      |> String.split("\n\n", trim: true)

    [a, b, c] =
      registers
      |> String.split("\n", trim: true)
      |> Enum.map(&String.split(&1, ~r/\D/, trim: true))
      |> List.flatten()
      |> Enum.map(&String.to_integer(&1))

    program =
      program
      |> String.split(~r/\D/, trim: true)
      |> Enum.map(&String.to_integer(&1))

    [%{"A" => a, "B" => b, "C" => c}, program]
  end
end

Tests - Parser

ExUnit.start(autorun: false)

defmodule ParserTest do
  use ExUnit.Case, async: true
  import Parser

  @input """
  Register A: 729
  Register B: 0
  Register C: 0

  Program: 0,1,5,4,3,0
  """
  @expected [
    %{
      "A" => 729,
      "B" => 0,
      "C" => 0
    },
    [0, 1, 5, 4, 3, 0]
  ]

  test "parse test" do
    assert parse(@input) == @expected
  end
end

ExUnit.run()

Part One

Code - Part 1

defmodule PartOne do
  def solve(input) do
    IO.puts("--- Part One ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    [registers, program] =
      input
      |> Parser.parse()

    compute(program, registers, [], 0)
    |> Enum.join(",")
  end

  def compute(program, regs, outs, ip) do
    routine = next_routine(program, ip)

    if length(routine) == 2 do
      [opcode, operand] = routine

      [regs, outs, ip] =
        case opcode do
          0 ->
            [adv(regs, operand), outs, ip + 2]

          1 ->
            [blx(regs, operand), outs, ip + 2]

          2 ->
            [bst(regs, operand), outs, ip + 2]

          3 ->
            [regs, outs, jnz(regs, operand, ip)]

          4 ->
            [bxc(regs, operand), outs, ip + 2]

          5 ->
            [regs, out(regs, operand, outs), ip + 2]

          6 ->
            [bdv(regs, operand), outs, ip + 2]

          7 ->
            [cdv(regs, operand), outs, ip + 2]
        end

      compute(program, regs, outs, ip)
    else
      outs
    end
  end

  def next_routine(program, ip) do
    program
    |> Enum.slice(ip, 2)
  end

  def get_combo_operand(regs, operand) do
    case operand do
      4 -> Map.get(regs, "A")
      5 -> Map.get(regs, "B")
      6 -> Map.get(regs, "C")
      7 -> nil
      _ -> operand
    end
  end

  def adv(regs, operand) do
    operand = get_combo_operand(regs, operand)
    Map.update!(regs, "A", &div(&1, 2 ** operand))
  end

  def blx(regs, operand) do
    Map.update!(regs, "B", &Bitwise.bxor(&1, operand))
  end

  def bst(regs, operand) do
    operand = get_combo_operand(regs, operand)

    Map.update!(regs, "B", fn _ ->
      Integer.mod(operand, 8)
      # |> Integer.to_string(8)
      # |> String.last()
      # |> String.to_integer(8)
    end)
  end

  def jnz(regs, operand, ip) do
    if Map.get(regs, "A") == 0 do
      ip + 2
    else
      operand
    end
  end

  def bxc(regs, _operand) do
    reg_c = Map.get(regs, "C")

    Map.update!(regs, "B", &Bitwise.bxor(&1, reg_c))
  end

  def out(regs, operand, outs) do
    operand = get_combo_operand(regs, operand)

    outs ++ [Integer.mod(operand, 8)]
  end

  def bdv(regs, operand) do
    operand = get_combo_operand(regs, operand)
    reg_a = Map.get(regs, "A")
    value = div(reg_a, 2 ** operand)

    Map.put(regs, "B", value)
  end

  def cdv(regs, operand) do
    operand = get_combo_operand(regs, operand)
    reg_a = Map.get(regs, "A")
    value = div(reg_a, 2 ** operand)

    Map.put(regs, "C", value)
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

defmodule PartOneTest do
  use ExUnit.Case, async: true
  import PartOne

  @input """
  Register A: 729
  Register B: 0
  Register C: 0

  Program: 0,1,5,4,3,0
  """
  @expected "4,6,3,5,6,3,5,2,1,0"

  test "part one" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 1

PartOne.solve(puzzle_input)

Part Two

Code - Part 2

defmodule PartTwo do
  def solve(input) do
    IO.puts("--- Part Two ---")
    IO.puts("Result: #{run(input)}")
  end

  def run(input) do
    [registers, program] =
      input
      |> Parser.parse()

    # The program run in base 8 (0..7)
    # I going to calculate the A register for each program 
    # instruction and then to use this result to adjust
    # the range for the next instruction

    program
    |> Enum.reverse()
    |> Enum.reduce({[], 0}, fn ins, {sub_program, sub_reg_a} ->
      sub_program = [ins | sub_program]

      if length(sub_program) <= 1 do
        sub_reg_a = 8**2

        {sub_program, sub_reg_a}
      else
        IO.puts("Sub program:")
        IO.inspect(sub_program)
        IO.puts("Register A:")
        IO.inspect(sub_reg_a)

        range =
          sub_reg_a
          |> Bitwise.<<<(3)
          |> (fn start -> start..(start + 8) end).()

        IO.puts("Range:")
        IO.inspect(range)

        sub_reg_a =
          range
          |> Enum.reduce_while(sub_reg_a, fn reg_a, acc ->
            registers = Map.put(registers, "A", reg_a)
            outs = PartOne.compute(sub_program, registers, [], 0)

            IO.inspect(reg_a)
            IO.inspect(outs)

            if sub_program == outs do
              {:halt, reg_a}
            else
              {:cont, acc}
            end
          end)

        IO.puts("Result:")
        IO.inspect(sub_reg_a)

        {sub_program, sub_reg_a}
      end
    end)
    |> elem(1)

    # 0..(8**2 - 1)
    # |> Enum.reduce_while(0, fn reg_a, acc ->
    #   # reg_a =
    #   #   program
    #   #   #|> Enum.reverse()
    #   #   |> Enum.join()
    #   #   |> String.trim("0")
    #   #   |> Kernel.<>(String.duplicate("0", n))
    #   #   |> IO.inspect()
    #   #   |> String.to_integer(8)

    #   registers = Map.put(registers, "A", reg_a)

    #   outs = PartOne.compute(program, registers, [], 0)

    #   IO.inspect(reg_a |> Integer.to_string(8))
    #   IO.inspect(outs)

    #   if program == outs do
    #     {:halt, reg_a}
    #   else
    #     {:cont, acc}
    #   end
    # end)
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

defmodule PartTwoTest do
  use ExUnit.Case, async: true
  import PartTwo

  @input """
  Register A: 2024
  Register B: 0
  Register C: 0

  Program: 0,3,5,4,3,0
  """
  @expected 117440

  test "part two" do
    assert run(@input) == @expected
  end
end

ExUnit.run()

Solution - Part 2

# 2,4,1,1,7,5,1,5,0,3,4,3,5,5,3,0
PartTwo.solve(puzzle_input)
[2, 4, 1, 1, 7, 5, 4, 4, 1, 4, 0, 3, 5, 5, 3, 0]