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

Advent of Code 2023 - Day 3

2023/elixir/livebooks/day03.livemd

Advent of Code 2023 - Day 3

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

Introduction

— Day 3: Gear Ratios —

You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside.

It doesn’t take long to find the gondolas, but there seems to be a problem: they’re not moving.

“Aaah!”

You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. “Sorry, I wasn’t expecting anyone! The gondola lift isn’t working right now; it’ll still be a while before I can fix it.” You offer to help.

The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing.

The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don’t really understand, but apparently any number adjacent to a symbol, even diagonally, is a “part number” and should be included in your sum. (Periods (.) do not count as a symbol.)

Here is an example engine schematic:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..

In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361.

Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic?

— Part Two —

The engineer finds the missing part and installs it in the engine! As the engine springs to life, you jump in the closest gondola, finally ready to ascend to the water source.

You don’t seem to be going very fast, though. Maybe something is still wrong? Fortunately, the gondola has a phone labeled “help”, so you pick it up and the engineer answers.

Before you can explain the situation, she suggests that you look out the window. There stands the engineer, holding a phone in one hand and waving with the other. You’re going so slowly that you haven’t even left the station. You exit the gondola.

The missing part wasn’t the only issue - one of the gears in the engine is wrong. A gear is any * symbol that is adjacent to exactly two part numbers. Its gear ratio is the result of multiplying those two numbers together.

This time, you need to find the gear ratio of every gear and add them all up so that the engineer can figure out which gear needs to be replaced.

Consider the same engine schematic again:

467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...$.*....
.664.598..

In this schematic, there are two gears. The first is in the top left; it has part numbers 467 and 35, so its gear ratio is 16345. The second gear is in the lower right; its gear ratio is 451490. (The * adjacent to 617 is not a gear because it is only adjacent to one part number.) Adding up all of the gear ratios produces 467835.

What is the sum of all of the gear ratios in your engine schematic?

Puzzle

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

Tools

Code - Tools

defmodule Tools do
  def get_size(matrix) do
    size_x = String.length(List.first(matrix))
    size_y = length(matrix)

    {size_x, size_y}
  end

  def get_value(matrix, {x, y}) do
    {size_x, size_y} = get_size(matrix)

    cond do
      x < 0 or x > size_x ->
        "."

      y < 0 or y > size_y ->
        "."

      true ->
        matrix
        |> Enum.at(y, "")
        |> String.at(x)

        # value =
        #   matrix
        #   |> Enum.at(y, "")
        #   |> String.at(x)

        # case value do
        #   nil -> "."
        #   _ -> value
        # end
    end
  end

  def get_type(matrix, point) do
    matrix
    |> get_value(point)
    |> get_type()
  end

  def get_type(value) do
    cond do
      Regex.match?(~r/^\d$/, value) ->
        :number

      value == "." ->
        :dot

      true ->
        :symbol
    end
  end

  def symbol?(matrix, {x, y}) do
    {size_x, size_y} = get_size(matrix)

    cond do
      x >= size_x or x < 0 ->
        false

      y >= size_y or y < 0 ->
        false

      true ->
        matrix
        |> get_value({x, y})
        |> symbol?()
    end
  end

  def symbol?(char) do
    case Regex.match?(~r/^\d$/, char) do
      true -> false
      false -> char != "."
    end
  end

  # def symbol_star?(matrix, {x, y}) do
  #   {size_x, size_y} = get_size(matrix)

  #   cond do
  #     x >= size_x or x < 0 ->
  #       false

  #     y >= size_y or y < 0 ->
  #       false

  #     true ->
  #       matrix
  #       |> get_value({x, y})
  #       |> symbol_mul?()
  #   end
  # end

  def symbol_star?(char) do
    Regex.match?(~r/^\*$/, char)
  end
end

Tests - Tools

ExUnit.start(autorun: false)

defmodule ToolsTest do
  use ExUnit.Case, async: true
  import Tools

  test "is a symbol?" do
    assert symbol?("2") == false
    assert symbol?(".") == false
    assert symbol?("$") == true
  end

  test "get char type" do
    assert get_type("2") == :number
    assert get_type(".") == :dot
    assert get_type("$") == :symbol
  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
    numbers = get_numbers(input)
    filters = get_filters(input)

    Enum.zip(numbers, filters)
    |> Enum.filter(fn {_, true?} -> true? end)
    |> Enum.map(fn {number, _} -> number end)
    |> Enum.sum()
  end

  def get_numbers(input) do
    Regex.scan(~r/\d+/, input)
    |> List.flatten()
    |> Enum.map(&amp;String.to_integer(&amp;1))
  end

  def get_filters(input) do
    matrix =
      input
      |> String.split("\n", trim: true)

    {size_x, size_y} = Tools.get_size(matrix)

    for y <- 0..(size_y - 1) do
      for x <- 0..(size_x - 1) do
        type =
          matrix
          |> Tools.get_type({x, y})

        case type do
          :number ->
            cond do
              Tools.symbol?(matrix, {x, y - 1}) -> "t"
              Tools.symbol?(matrix, {x + 1, y - 1}) -> "t"
              Tools.symbol?(matrix, {x + 1, y}) -> "t"
              Tools.symbol?(matrix, {x + 1, y + 1}) -> "t"
              Tools.symbol?(matrix, {x, y + 1}) -> "t"
              Tools.symbol?(matrix, {x - 1, y + 1}) -> "t"
              Tools.symbol?(matrix, {x - 1, y}) -> "t"
              Tools.symbol?(matrix, {x - 1, y - 1}) -> "t"
              true -> "f"
            end

          _ ->
            "."
        end
      end
    end
    |> Enum.map(&amp;Enum.join(&amp;1))
    |> Enum.join(".")
    |> String.split(~r/\.+/, trim: true)
    |> Enum.map(&amp;String.contains?(&amp;1, "t"))
  end
end

Tests - Part 1

ExUnit.start(autorun: false)

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

  @input """
  467..114..
  ...*......
  ..35..633.
  ......#...
  617*......
  .....+.58.
  ..592.....
  ......755.
  ...$.*....
  .664.598..
  """

  @numbers [467, 114, 35, 633, 617, 58, 592, 755, 664, 598]

  test "get numbers" do
    assert get_numbers(@input) == @numbers
  end

  @filters [true, false, true, true, true, false, true, true, true, true]

  test "get filters" do
    assert get_filters(@input) == @filters
  end

  @expected 4361

  test "part one" do
    actual = run(@input)
    assert actual == @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
    matrix =
      input
      |> String.split("\n", trim: true)

    point_map = gen_point_map(input)

    {size_x, size_y} = Tools.get_size(matrix)

    for y <- 0..(size_y - 1), reduce: 0 do
      acc1 ->
        for x <- 0..(size_x - 1), reduce: acc1 do
          acc2 ->
            case Tools.get_value(matrix, {x, y}) do
              "*" ->
                ops = find_operators(matrix, point_map, {x, y})

                case length(ops) do
                  size when size > 1 -> acc2 + Enum.product(ops)
                  _ -> acc2
                end

              _ ->
                acc2
            end
        end
    end
  end

  defp find_operators(matrix, point_map, {x, y}) do
    [
      {x, y - 1},
      {x + 1, y - 1},
      {x + 1, y},
      {x + 1, y + 1},
      {x, y + 1},
      {x - 1, y + 1},
      {x - 1, y},
      {x - 1, y - 1}
    ]
    |> Enum.map(&amp;{&amp;1, Tools.get_value(matrix, &amp;1)})
    |> Enum.filter(fn {_, val} ->
      if Tools.get_type(val) == :number, do: true, else: false
    end)
    |> Enum.map(fn {point, _} -> point_map[point] end)
    |> Enum.uniq()
  end

  def gen_point_map(input) do
    matrix =
      input
      |> String.split("\n", trim: true)

    {_size_x, size_y} =
      matrix
      |> Tools.get_size()

    for y <- 0..(size_y - 1), reduce: %{} do
      map ->
        line =
          matrix
          |> Enum.at(y)

        indexes =
          Regex.scan(~r/\d+/, line, return: :index)
          |> List.flatten()

        numbers =
          Regex.scan(~r/\d+/, line)
          |> List.flatten()
          |> Enum.map(&amp;String.to_integer(&amp;1))

        new_map =
          Enum.zip(indexes, numbers)
          |> Enum.map(fn {{x, offset}, number} ->
            0..(offset - 1)
            |> Enum.map(&amp;{{x + &amp;1, y}, number})
            |> Map.new()
          end)
          |> Enum.reduce(%{}, fn item, acc ->
            Map.merge(acc, item)
          end)

        Map.merge(map, new_map)
    end
  end
end

Tests - Part 2

ExUnit.start(autorun: false)

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

  @input1 """
  467..114..
  ...*......
  ..35..633.
  """

  @expected1 %{
    {0, 0} => 467,
    {1, 0} => 467,
    {2, 0} => 467,
    {5, 0} => 114,
    {6, 0} => 114,
    {7, 0} => 114,
    {2, 2} => 35,
    {3, 2} => 35,
    {6, 2} => 633,
    {7, 2} => 633,
    {8, 2} => 633
  }

  test "gen point number to map" do
    assert gen_point_map(@input1) == @expected1
  end

  @input """
  467..114..
  ...*......
  ..35..633.
  ......#...
  617*......
  .....+.58.
  ..592.....
  ......755.
  ...$.*....
  .664.598..
  """
  @expected 467_835

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

ExUnit.run()

Solution - Part 2

PartTwo.solve(puzzle_input)