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

Day 7

livebook/7.livemd

Day 7

Part 1

# input = File.stream!("7/example.txt")
input = File.stream!("7/input.txt")
defmodule U do
  def parse(l) do
    [_, sum, list] = Regex.run(~r/(\d+):\s*((?:\d+\s*)+)/, l)

    list = Enum.map(String.split(list), &String.to_integer/1)
    {String.to_integer(sum), list}
  end
end
data = input |> Enum.map(&U.parse/1)
defmodule P1 do
  def is_calculated(exp, [exp]), do: true
  def is_calculated(_, [_]), do: false
  def is_calculated(exp, [n1, n2 | tail]) do
    is_calculated(exp, [n1 + n2 | tail]) || is_calculated(exp, [n1 * n2 | tail])
  end
end
Enum.reduce(data, 0, fn {exp, numbers}, sum ->
  if P1.is_calculated(exp, numbers) do
    sum + exp 
  else 
    sum
  end
end)
defmodule P2 do
  def is_calculated(exp, [exp]), do: true
  def is_calculated(_, [_]), do: false

  def is_calculated(exp, [n1, n2 | tail]) do
    is_calculated(exp, [n1 + n2 | tail]) ||
      is_calculated(exp, [n1 * n2 | tail]) ||
      is_calculated(exp, [
        (Integer.to_string(n1) <> Integer.to_string(n2)) |> String.to_integer() | tail
      ])
  end
end
Enum.reduce(data, 0, fn {exp, numbers}, sum ->
  if P2.is_calculated(exp, numbers) do
    sum + exp 
  else 
    sum
  end
end)