Mull It Over
Mix.install([{:kino, "~> 0.14.2"}])
Input
input = Kino.Input.textarea("Input:")
input = Kino.Input.read(input)
Part 1
muls = Regex.scan(~r"mul\(\d+,\d+\)", input)
instructions =
Enum.map(muls, fn [m] ->
[_, a, b] = Regex.run(~r"mul\((\d+),(\d+)\)", m)
{String.to_integer(a), String.to_integer(b)}
end)
Enum.reduce(instructions, 0, fn {a, b}, c -> a * b + c end)
Part 2
instructions =
Regex.scan(~r"mul\(\d+,\d+\)|don't|do", input)
|> Enum.map(fn
["mul" <> args] ->
[_, a, b] = Regex.run(~r"\((\d+),(\d+)\)", args)
{:mul, {String.to_integer(a), String.to_integer(b)}}
["don't"] ->
:disable
["do"] ->
:enable
end)
interpret = fn
{:mul, {a, b}}, {:enabled, acc} -> {:enabled, acc + a * b}
{:mul, _}, {:disabled, acc} -> {:disabled, acc}
:enable, {_, acc} -> {:enabled, acc}
:disable, {_, acc} -> {:disabled, acc}
end
Enum.reduce(instructions, {:enabled, 0}, interpret)