mirror of
https://github.com/rjNemo/ai_advent_code_2024
synced 2026-06-11 13:06:40 +00:00
feat: Improve Day03 solution with robust file handling and parsing
This commit is contained in:
parent
5958552501
commit
a9db3bc044
1 changed files with 15 additions and 13 deletions
|
|
@ -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()
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue