Solve day 1
This commit is contained in:
parent
a20b32f7bd
commit
36bb25c4da
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,6 @@
|
|||
3 4
|
||||
4 3
|
||||
2 5
|
||||
1 3
|
||||
3 9
|
||||
3 3
|
||||
|
|
@ -0,0 +1 @@
|
|||
[].
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
-module(day_1).
|
||||
-export([part_1/0, part_2/0]).
|
||||
|
||||
part_1() ->
|
||||
File = open_file(),
|
||||
part_1(File).
|
||||
|
||||
part_1(File) ->
|
||||
[Left, Right] = parse_input(File),
|
||||
SortedLeft = lists:sort(Left),
|
||||
SortedRight = lists:sort(Right),
|
||||
Zipped = lists:zip(SortedLeft, SortedRight),
|
||||
Distances = lists:map(fun({L, R}) -> abs(L - R) end, Zipped),
|
||||
lists:sum(Distances).
|
||||
|
||||
part_2() ->
|
||||
File = open_file(),
|
||||
part_2(File).
|
||||
|
||||
part_2(File) ->
|
||||
[Left, Right] = parse_input(File),
|
||||
RightCounts = lists:foldl(
|
||||
fun(R, M) -> maps:update_with(R, fun(V) -> V + 1 end, 1, M) end,
|
||||
#{},
|
||||
Right),
|
||||
Similarities = lists:map(fun(L) -> L * maps:get(L, RightCounts, 0) end, Left),
|
||||
lists:sum(Similarities).
|
||||
|
||||
%% Private Functions
|
||||
|
||||
open_file() ->
|
||||
Filename = filename:absname("./priv/input/1.txt"),
|
||||
open_file(Filename).
|
||||
|
||||
open_file(Filename) ->
|
||||
{ok, File} = file:open(Filename, read),
|
||||
File.
|
||||
|
||||
parse_input(Filehandle) ->
|
||||
[Left, Right] = read_numbers_from_line(Filehandle),
|
||||
parse_input(Filehandle, [Left], [Right]).
|
||||
|
||||
parse_input(Filehandle, FirstList, SecondList) ->
|
||||
case read_numbers_from_line(Filehandle) of
|
||||
[Left, Right] ->
|
||||
parse_input(Filehandle, [Left | FirstList], [Right | SecondList]);
|
||||
eof ->
|
||||
[FirstList, SecondList]
|
||||
end.
|
||||
|
||||
read_numbers_from_line(Filehandle) ->
|
||||
case file:read_line(Filehandle) of
|
||||
{ok, Line} ->
|
||||
[Left, Right] = string:split(Line, " "),
|
||||
{LeftNum, _} = string:to_integer(string:trim(Left)),
|
||||
{RightNum, _} = string:to_integer(string:trim(Right)),
|
||||
[LeftNum, RightNum];
|
||||
eof ->
|
||||
eof
|
||||
end.
|
||||
|
||||
%% TESTS
|
||||
|
||||
-ifdef(TEST).
|
||||
-include_lib("eunit/include/eunit.hrl").
|
||||
|
||||
part_1_test() ->
|
||||
TestFile = test_data(),
|
||||
?assertEqual(11, part_1(TestFile)).
|
||||
|
||||
part_2_test() ->
|
||||
TestFile = test_data(),
|
||||
?assertEqual(31, part_2(TestFile)).
|
||||
|
||||
test_data() ->
|
||||
open_file("./priv/test_input/1.txt").
|
||||
|
||||
-endif.
|
||||
Loading…
Reference in New Issue