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

Day 7: Bridge Repair

day07.livemd

Day 7: Bridge Repair

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

Input

input = Kino.Input.textarea("Please, paste your input:")
defmodule Day7Shared do
  def parse(input) do
    input
    |> Kino.Input.read()
    |> String.split("\n")
    |> Enum.map(fn line ->
      [result | operands] =
        Regex.scan(~r/\d+/, line)
        |> List.flatten()
        |> Enum.map(&String.to_integer/1)

      {result, operands}
    end)
  end

  def generate_combinations(possible_values, length) do
    if length == 1 do
      Enum.map(possible_values, fn x -> [x] end)
    else
      for head <- possible_values,
          tail <- generate_combinations(possible_values, length - 1) do
        [head | tail]
      end
    end
  end
end

# Day7Shared.parse(input)
# Day7Shared.generate_combinations(["+", "*"], 3)

Part 1

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?

defmodule Day7Part1 do
  import Day7Shared, only: [generate_combinations: 2]

  @possible_operators [:add, :multi]

  def process(equations) do
    equations
    |> Enum.filter(fn {result, [head | tail] = _operands} ->
      @possible_operators
      |> generate_combinations(length(tail))
      |> Stream.map(&amp;Enum.zip(&amp;1, tail))
      |> Enum.any?(&amp;(calc(&amp;1, head) == result))
    end)
    |> Enum.reduce(0, fn {result, _}, acc -> acc + result end)
  end

  def calc([], acc), do: acc
  def calc([{:add, operand} | tail], acc), do: calc(tail, acc + operand)
  def calc([{:multi, operand} | tail], acc), do: calc(tail, acc * operand)
end

input |> Day7Shared.parse() |> Day7Part1.process()

# 2437272016585 is the right answer
# dumb brute-force approach takes ~95ms
# with Task.async_stream it takes ~55ms
# (but left a dumb approach in the code for Part 1, see example of Task-one in the Part 2)

Part 2

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?

defmodule Day7Part2 do
  import Day7Shared, only: [generate_combinations: 2]

  @possible_operators [:add, :multi, :concat]

  def process(equations) do
    equations
    |> Task.async_stream(fn {result, [head | tail] = _operands} ->
      is_any =
        @possible_operators
        |> generate_combinations(length(tail))
        |> Stream.map(&amp;Enum.zip(&amp;1, tail))
        |> Enum.any?(&amp;(calc(&amp;1, head) == result))

      {is_any, result}
    end)
    |> Enum.reduce(0, fn
      {:ok, {true, result}}, acc -> acc + result
      {:ok, _}, acc -> acc
    end)
  end

  def calc([], acc), do: acc

  def calc([{:add, operand} | tail], acc),
    do: calc(tail, acc + operand)

  def calc([{:multi, operand} | tail], acc),
    do: calc(tail, acc * operand)

  def calc([{:concat, operand} | tail], acc),
    do: calc(tail, Enum.join([acc, operand]) |> String.to_integer())
end

input |> Day7Shared.parse() |> Day7Part2.process()

# 162987117690649 is the right answer
# dumb brute-force approach takes ~12 seconds
# with Task.async_stream it takes ~1.7 seconds