feat: Add file reading and parsing functions for Day 1 puzzle solution

This commit is contained in:
Ruidy (aider) 2024-12-01 10:00:12 +01:00 committed by Ruidy
parent 8346a50620
commit d382b3e31c
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
3 changed files with 1044 additions and 0 deletions

1000
day1/input.txt Normal file

File diff suppressed because it is too large Load diff

View file

@ -3,6 +3,37 @@ defmodule AdventCode2024 do
Documentation for `AdventCode2024`.
"""
@doc """
Reads the input file for day 1 and calculates the total distance between the two lists.
Returns {:ok, result} if successful, {:error, reason} if there's an error.
"""
def solve_day1(input_file \\ "day1/input.txt") do
case File.read(input_file) do
{:ok, content} ->
{left_list, right_list} = parse_input(content)
result = calculate_total_distance(left_list, right_list)
{:ok, result}
{:error, reason} -> {:error, reason}
end
end
@doc """
Parses the input string into two lists of numbers.
Input format is expected to be tab-separated numbers, one pair per line.
"""
def parse_input(content) do
{left, right} =
content
|> String.split("\n", trim: true)
|> Enum.map(&String.split(&1, ~r/\s+/, trim: true))
|> Enum.map(fn [left, right] ->
{String.to_integer(left), String.to_integer(right)}
end)
|> Enum.unzip()
{left, right}
end
@doc """
Calculates the total distance between two lists of numbers.
Lists are first sorted, then paired up, and the absolute differences are summed.

View file

@ -3,6 +3,19 @@ defmodule AdventCode2024Test do
doctest AdventCode2024
describe "Day 1: Historian Hysteria" do
test "solves day 1 puzzle with actual input file" do
assert {:ok, result} = AdventCode2024.solve_day1()
assert is_integer(result)
end
test "handles missing input file" do
assert {:error, :enoent} = AdventCode2024.solve_day1("nonexistent.txt")
end
test "parses input string correctly" do
input = "1\t2\n3\t4\n5\t6"
assert {[1, 3, 5], [2, 4, 6]} = AdventCode2024.parse_input(input)
end
test "calculates total distance between two lists using example input" do
left_list = [3, 4, 2, 1, 3, 3]
right_list = [4, 3, 5, 3, 9, 3]