AdventOfCodeSolutions/2024/day1/part1.erl

24 lines
723 B
Erlang
Raw Normal View History

2024-12-04 10:30:01 -05:00
-module(day1).
-export([main/0]).
main() ->
{ok, Content} = file:read_file("input.txt"),
Lines = string:split(string:trim(Content), "\n", all),
{List1, List2} = lists:foldl(fun parse_line/2, {[], []}, Lines),
SortedList1 = lists:sort(List1),
SortedList2 = lists:sort(List2),
Distance = calculate_distance(SortedList1, SortedList2),
io:format("Result: ~p~n", [Distance]).
parse_line(Line, {Acc1, Acc2}) ->
[Str1, Str2] = string:split(string:trim(Line), " ", all),
{Num1, _} = string:to_integer(Str1),
{Num2, _} = string:to_integer(Str2),
{[Num1 | Acc1], [Num2 | Acc2]}.
calculate_distance(List1, List2) ->
lists:sum([abs(A - B) || {A, B} <- lists:zip(List1, List2)]).