Powered by AppSignal & Oban Pro

d07

d07/d07.livemd

d07

Section

defmodule D07 do
  def parse(input) do
    for line <- String.split(input, "\n", trim: true) do
      [lhs, rhs] = String.split(line, ": ")
      operands = String.split(rhs) |> Enum.map(&String.to_integer/1)
      {String.to_integer(lhs), operands}
    end
  end

  defp enumerate([x | xs], ops \\ [:+, :*]) do
    Enum.reduce(xs, [x], fn y, accs ->
      Enum.flat_map(accs, fn acc ->
        Enum.map(ops, fn
          :+ -> y + acc
          :* -> y * acc
          :<> -> String.to_integer("#{acc}#{y}")
        end)
      end)
    end)
  end

  def part1(equations) do
    for {value, operands} <- equations do
      if Enum.member?(enumerate(operands), value), do: value, else: 0
    end
    |> Enum.sum()
  end

  def part2(equations) do
    for {value, operands} <- equations do
      if Enum.member?(enumerate(operands, [:+, :*, :<>]), value), do: value, else: 0
    end
    |> Enum.sum()
  end
end

sample = "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
"

D07.part1(D07.parse(sample))
ExUnit.start()

defmodule D07.Test do
  use ExUnit.Case

  test "sample" do
    sample = "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
"
    equations = D07.parse(sample)
    assert 3749 == D07.part1(equations)
    assert 11387 == D07.part2(equations)
  end
end

ExUnit.run()
input = File.read!(__DIR__ <> "/input")
equations = D07.parse(input)
D07.part1(equations)
D07.part2(equations)