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

Day 3: Gear Ratios

day03.livemd

Day 3: Gear Ratios

Mix.install([
  {:kino, "~> 0.11.3"}
])

Input

input = Kino.Input.textarea("Please paste your input:")
defmodule Day3Shared do
  def parse(input) do
    input
    |> Kino.Input.read()
    |> String.split("\n", trim: true)
    |> Enum.with_index()
    |> Enum.reduce(%{}, fn {line, y}, map ->
      numbers_positions =
        ~r/\d+/
        |> Regex.scan(line, return: :index)
        |> List.flatten()

      line
      |> String.split("", trim: true)
      |> Enum.with_index()
      |> Enum.reduce(map, fn {value, x}, map ->
        map
        |> Map.put({x, y}, value)
        |> Map.update(:max_x, x, &max(&1, x))
        |> Map.update(:max_y, y, &max(&1, y))
      end)
      |> Map.update(:numbers, %{y => numbers_positions}, fn nums ->
        Map.put(nums, y, numbers_positions)
      end)
    end)
  end

  def neib({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}
    ]
  end

  def number_coords({start_x, len}, y) do
    start_x..(start_x + len - 1)
    |> Enum.map(&{&1, y})
  end

  def number_to_integer({start_x, len}, y, engine_map) do
    start_x..(start_x + len - 1)
    |> Enum.map(&Map.get(engine_map, {&1, y}))
    |> Enum.map(&String.to_integer/1)
    |> Integer.undigits()
  end
end

Day3Shared.parse(input)

Part 1

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?

defmodule Day3Part1 do
  @skippable ~w[1 2 3 4 5 6 7 8 9 0 .]

  def solve(%{numbers: all_numbers} = engine_map) do
    all_numbers
    |> Enum.map(fn {y, line_numbers} ->
      adjacenting =
        line_numbers
        |> Enum.filter(fn {s_x, len} ->
          s_x..(s_x + len - 1)
          |> Enum.any?(fn x ->
            {x, y}
            |> Day3Shared.neib()
            |> Enum.any?(fn pos ->
              val = Map.get(engine_map, pos, ".")
              val not in @skippable
            end)
          end)
        end)

      {y, adjacenting}
    end)
    |> Enum.filter(&(length(elem(&1, 1)) > 0))
    |> Enum.reduce(0, fn {y, nums}, acc ->
      nums
      |> Enum.map(&Day3Shared.number_to_integer(&1, y, engine_map))
      |> Enum.sum()
      |> Kernel.+(acc)
    end)
  end
end

input
|> Day3Shared.parse()
|> Day3Part1.solve()

Part 2

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?

defmodule Day3Part2 do
  @digits ~w[1 2 3 4 5 6 7 8 9 0]

  def solve(%{numbers: all_numbers} = engine_map) do
    engine_map
    |> Enum.filter(fn {_, value} -> value == "*" end)
    |> Enum.filter(fn {pos, _} ->
      pos
      |> Day3Shared.neib()
      |> Enum.count(&(Map.get(engine_map, &1) in @digits))
      |> Kernel.>(1)
    end)
    |> Enum.map(fn {{x, y}, _} ->
      possible_rows = [y - 1, y, y + 1]

      all_numbers
      |> Enum.filter(fn {y, _} -> y in possible_rows end)
      |> Enum.map(fn {y, numbers} ->
        numbers
        |> Enum.filter(fn num ->
          num
          |> Day3Shared.number_coords(y)
          |> Enum.any?(fn coord -> coord in Day3Shared.neib({x, y}) end)
        end)
        |> Enum.map(&Day3Shared.number_to_integer(&1, y, engine_map))
      end)
      |> List.flatten()
    end)
    |> Enum.filter(&(length(&1) == 2))
    |> Enum.map(fn [a, b] -> a * b end)
    |> Enum.sum()
  end
end

input
|> Day3Shared.parse()
|> Day3Part2.solve()