advent_of_code/lib/day03.ex
2024-12-05 22:07:08 +01:00

73 lines
2.0 KiB
Elixir

defmodule AdventOfCode.Day03 do
def part1() do
input = File.read!("./priv/day03.part1.txt")
regex = ~r/mul\((\d{1,3}),(\d{1,3})\)/
instructions = Regex.scan(regex, input)
Enum.reduce(instructions, 0, fn instruction, sum ->
[_, left, right] = instruction
left = String.to_integer(left)
right = String.to_integer(right)
sum + left * right
end)
end
def part2() do
input = File.read!("./priv/day03.part2.txt")
String.graphemes(input)
|> Enum.with_index()
|> Enum.reduce({0, true}, fn {letter, index}, {sum, enable_instruction} ->
case letter do
"m" ->
{_head, substr} = String.split_at(input, index)
case :binary.match(substr, ")") do
{position, _length} ->
instruction = String.slice(substr, 0, position + 1)
case String.length(instruction) <= 12 and
Regex.scan(~r/mul\((\d{1,3}),(\d{1,3})\)/, instruction) do
[[_, left, right]] ->
left = String.to_integer(left)
right = String.to_integer(right)
IO.inspect(instruction)
IO.inspect(left)
IO.inspect(right)
IO.inspect(enable_instruction)
case enable_instruction do
true ->
{sum + left * right, enable_instruction}
false ->
{sum, enable_instruction}
end
_ ->
{sum, enable_instruction}
end
:nomatch ->
{sum, enable_instruction}
end
"d" ->
substr = String.slice(input, index, String.length("don't()"))
cond do
substr == "don't()" ->
{sum, false}
String.starts_with?(substr, "do()") ->
{sum, true}
end
_ ->
{sum, enable_instruction}
end
end)
end
end