AoC
Day 3
# input = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
input = File.read!("3/input.txt")
defmodule U do
def parse_mul([_, n1, n2]) do
{String.to_integer(n1), String.to_integer(n2)}
end
end
r = ~r/mul\((\d{1,3}),(\d{1,3})\)/
r |> Regex.scan(input) |> Enum.map(&U.parse_mul/1) |> Enum.reduce(0, fn {a, b}, s -> s + (a * b) end)
Part 2
defmodule U2 do
def parse_mul([_, "mul", n1, n2]) do
{:mul, String.to_integer(n1), String.to_integer(n2)}
end
def parse_mul([_, "", "", "", "do"]) do
:do
end
def parse_mul([_, "", "", "", "", "don't"]) do
:dont
end
end
r = ~r/(mul)\((\d{1,3}),(\d{1,3})\)|(do)\(\)|(don't)\(\)/
r
|> Regex.scan(input)
|> Enum.map(&U2.parse_mul/1)
|> Enum.reduce(
{0, true},
fn
{:mul, a, b}, {s, true} -> {s + a * b, true}
{:mul, _, _}, {s, false} -> {s, false}
:do, {s, _} -> {s, true}
:dont, {s, _} -> {s, false}
end
)