Solve day 3

This commit is contained in:
Aurélien Geron
2024-12-07 16:32:10 +13:00
parent 788e01b7bb
commit 005fe680cf
2 changed files with 40 additions and 7 deletions
+20 -7
View File
@@ -1,13 +1,26 @@
defmodule Aoc2024.Day03 do
def parse(input) do
input |> String.split("\n", trim: true)
def part1(instructions) do
~r/mul\(([0-9]+),([0-9]+)\)/
|> Regex.scan(instructions)
|> Enum.map(fn [_all, num1_str, num2_str] ->
case {Integer.parse(num1_str), Integer.parse(num2_str)} do
{{num1, ""}, {num2, ""}} -> num1 * num2
_ -> 0
end
end)
|> Enum.sum()
end
def part1(_lines) do
:todo1
end
def part2(instructions) do
conditional_instructions =
~r/don't\(\).*?do\(\)/s
|> Regex.replace(instructions, "|")
def part2(_lines) do
:todo2
# handle possible case where the instructions end with don't() and more mul
conditional_instructions2 =
~r/don't\(\).*$/s
|> Regex.replace(conditional_instructions, "|")
part1(conditional_instructions2)
end
end
+20
View File
@@ -31,4 +31,24 @@ defmodule Aoc2024Test do
assert Aoc2024.Day02.part1(parsed_input) == 2
assert Aoc2024.Day02.part2(parsed_input) == 4
end
test "Day 3 - part 1" do
input = "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"
assert Aoc2024.Day03.part1(input) == 161
end
test "Day 3 - part 2" do
input = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"
assert Aoc2024.Day03.part2(input) == 48
end
test "Day 3 - part 2 end with don't" do
input = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)un?mul(8,5))"
assert Aoc2024.Day03.part2(input) == 8
end
test "Day 3 - part 2 support newlines within don't()...do() blocks" do
input = "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)\n+mul(32,64](mul(11,8)undo()?mul(8,5))"
assert Aoc2024.Day03.part2(input) == 48
end
end