feat: Improve Day03 solution with robust file handling and parsing

This commit is contained in:
Ruidy (aider) 2024-12-03 14:10:00 +01:00
parent 5958552501
commit a9db3bc044
No known key found for this signature in database
GPG key ID: E00F51288CB857CC

View file

@ -13,16 +13,15 @@ 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
cond do if String.contains?(input, "/") and not String.contains?(input, "\n") do
# If it looks like a file path and doesn't contain newlines # Input is a file path
String.contains?(input, "/") and not String.contains?(input, "\n") -> case File.read(input) do
case File.read(input) do {:ok, content} -> solve_content(content)
{:ok, content} -> solve_content(content) {:error, reason} -> {:error, reason}
{:error, reason} -> {:error, reason} end
end else
# If it's not a file path or contains newlines, treat as content # Input is content
true -> solve_content(input)
solve_content(input)
end end
end end
@ -52,9 +51,12 @@ defmodule AdventCode2024.Solutions.Day03 do
~r/mul\((\d{1,3}),(\d{1,3})\)/ ~r/mul\((\d{1,3}),(\d{1,3})\)/
|> Regex.scan(content, capture: :all_but_first) |> Regex.scan(content, capture: :all_but_first)
|> Enum.map(fn [x, y] -> |> Enum.map(fn [x, y] ->
{x_int, _} = Integer.parse(x) with {x_int, ""} <- Integer.parse(x),
{y_int, _} = Integer.parse(y) {y_int, ""} <- Integer.parse(y) do
x_int * y_int x_int * y_int
else
_ -> 0
end
end) end)
|> Enum.sum() |> Enum.sum()