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

Advent of Code 2024 - Day 7

2024/elixir/livebooks/day07.livemd

Advent of Code 2024 - Day 7

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

Introduction

— Day 7: Bridge Repair —

The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn’t on this side of the bridge, though; maybe he’s on the other side?

When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won’t be able to cross until it’s fixed.

You ask how long it’ll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input).

For example:

190: 10 19
3267: 81 40 27
83: 17 5
156: 15 6
7290: 6 8 6 15
161011: 16 10 13
192: 17 8 14
21037: 9 7 18 13
292: 11 6 16 20

Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value.

Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*).

Only three of the above equations can be made true by inserting operators:

  • 190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190).
  • 3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)!
  • 292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20.

The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749.

Determine which equations could possibly be true. What is their total calibration result?

— Part Two —

The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator.

The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right.

Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators:

  • 156: 15 6 can be made true through a single concatenation: 15 || 6 = 156.
  • 7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15.
  • 192: 17 8 14 can be made true using 17 || 8 + 14.

Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387.

Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?

Puzzle

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

Parser

Code - Parser

defmodule Parser do
  def parse(input) do
    input
    |> String.split("\n", trim: true)
    |> Enum.map(&String.split(&1, ": ", trim: true))
    |> Enum.map(fn [result, equation] ->
      result =
        result
        |> String.to_integer()

      equation =
        equation
        |> String.split(" ")
        |> Enum.map(&String.to_integer(&1))

      {result, equation}
    end)
  end
end

Tests - Parser

ExUnit.start(autorun: false)

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

  @input """
  190: 10 19
  3267: 81 40 27
  83: 17 5
  156: 15 6
  7290: 6 8 6 15
  161011: 16 10 13
  192: 17 8 14
  21037: 9 7 18 13
  292: 11 6 16 20
  """
  @expected [
    {190, [10, 19]},
    {3267, [81, 40, 27]},
    {83, [17, 5]},
    {156, [15, 6]},
    {7290, [6, 8, 6, 15]},
    {161_011, [16, 10, 13]},
    {192, [17, 8, 14]},
    {21037, [9, 7, 18, 13]},
    {292, [11, 6, 16, 20]}
  ]

  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
    input
    |> Parser.parse()
    |> Enum.map(fn {result, equation} ->
      {result, valid_equation?(result, equation)}
    end)
    |> Enum.filter(fn {_, validations} -> Enum.any?(validations) end)
    |> Enum.map(fn {result, _} -> result end)
    |> Enum.sum()
  end

  def valid_equation?(result, equation) do
    exp = length(equation) - 1

    0..(2 ** exp - 1)
    |> Enum.map(fn num ->
      ops =
        num
        |> Integer.to_string(2)
        |> String.pad_leading(exp, "0")
        |> String.codepoints()

      [first_val | rest] = equation

      new_result =
        Enum.zip(ops, rest)
        |> Enum.reduce(first_val, fn {op, val}, acc ->
          # "0" -> +
          # "1" -> *
          case op do
            "0" -> acc + val
            "1" -> acc * val
          end
        end)

      result == new_result
    end)
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

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

  @input """
  190: 10 19
  3267: 81 40 27
  83: 17 5
  156: 15 6
  7290: 6 8 6 15
  161011: 16 10 13
  192: 17 8 14
  21037: 9 7 18 13
  292: 11 6 16 20
  """
  @expected 3749

  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
    input
    |> Parser.parse()
    |> Enum.map(fn {result, equation} ->
      {result, valid_equation?(result, equation)}
    end)
    |> Enum.filter(fn {_, validations} -> Enum.any?(validations) end)
    |> Enum.map(fn {result, _} -> result end)
    |> Enum.sum()
  end

  def valid_equation?(result, equation) do
    exp = length(equation) - 1

    0..(3 ** exp - 1)
    |> Enum.map(fn num ->
      ops =
        num
        |> Integer.to_string(3)
        |> String.pad_leading(exp, "0")
        |> String.codepoints()

      [first_val | rest] = equation

      new_result =
        Enum.zip(ops, rest)
        |> Enum.reduce(first_val, fn {op, val}, acc ->
          # "0" -> +
          # "1" -> *
          # "2" -> ||
          case op do
            "0" -> acc + val
            "1" -> acc * val
            "2" -> concat(acc, val)
          end
        end)

      result == new_result
    end)
  end

  def concat(a, b) do
    "#{a}#{b}"
    |> String.to_integer()
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

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

  @input """
  190: 10 19
  3267: 81 40 27
  83: 17 5
  156: 15 6
  7290: 6 8 6 15
  161011: 16 10 13
  192: 17 8 14
  21037: 9 7 18 13
  292: 11 6 16 20
  """
  @expected 11387

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

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)