fix: Improve file handling and instruction parsing in Day03 solution

This commit is contained in:
Ruidy (aider) 2024-12-03 14:21:23 +01:00
parent 17c17fb4fb
commit e1f4afe639
No known key found for this signature in database
GPG key ID: E00F51288CB857CC

View file

@ -13,15 +13,17 @@ defmodule AdventCode2024.Solutions.Day03 do
def solve(input \\ @default_input) def solve(input \\ @default_input)
def solve(""), do: {:error, :no_input} def solve(""), do: {:error, :no_input}
def solve(input) when is_binary(input) and input != "" do def solve(input) when is_binary(input) and input != "" do
if String.contains?(input, "/") and not String.contains?(input, "\n") do cond do
# Input is a file path # Check if it looks like a file path and try to read it
case File.read(input) do String.contains?(input, "/") and not String.contains?(input, "\n") ->
{:ok, content} -> solve_content(content) case File.read(input) do
{:error, reason} -> {:error, reason} {:ok, content} -> solve_content(content)
end {:error, reason} -> {:error, reason}
else end
# Input is content
solve_content(input) # Treat as direct content
true ->
solve_content(input)
end end
end end
@ -31,15 +33,17 @@ defmodule AdventCode2024.Solutions.Day03 do
def solve_part2(input \\ @default_input) def solve_part2(input \\ @default_input)
def solve_part2(""), do: {:error, :no_input} def solve_part2(""), do: {:error, :no_input}
def solve_part2(input) when is_binary(input) and input != "" do def solve_part2(input) when is_binary(input) and input != "" do
if String.contains?(input, "\n") or !String.contains?(input, "/") do cond do
# Input is content # Check if it looks like a file path and try to read it
solve_part2_content(input) String.contains?(input, "/") and not String.contains?(input, "\n") ->
else case File.read(input) do
# Input is file path {:ok, content} -> solve_part2_content(content)
case File.read(input) do {:error, reason} -> {:error, reason}
{:ok, content} -> solve_part2_content(content) end
{:error, reason} -> {:error, reason}
end # Treat as direct content
true ->
solve_part2_content(input)
end end
end end
@ -71,8 +75,9 @@ defmodule AdventCode2024.Solutions.Day03 do
defp process_multiplications(content) do defp process_multiplications(content) do
# Split content into tokens that match either multiplication or control instructions # Split content into tokens that match either multiplication or control instructions
tokens = Regex.scan(~r/(?:mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\))/, content) tokens = Regex.scan(~r/(?:mul\(\d{1,3},\d{1,3}\)|do\(\)|don't\(\))|(?:do|don't)\(\)/, content)
|> List.flatten() |> List.flatten()
|> Enum.filter(&(&1 in ["do()", "don't()"] or String.starts_with?(&1, "mul(")))
# Process tokens in order, tracking multiplication state # Process tokens in order, tracking multiplication state
tokens tokens