74 lines
1.7 KiB
Erlang
74 lines
1.7 KiB
Erlang
%% to compile: erlc day3A.erl
|
|
%% to run: erl -noshell -s day5 solve
|
|
%%
|
|
-module(day6).
|
|
|
|
-export ([solve/0, solve/1, solve/2]).
|
|
-export ([read_input/0]).
|
|
|
|
solve() ->
|
|
solve(['1']),
|
|
solve(['2']),
|
|
init:stop().
|
|
|
|
solve(A) ->
|
|
solve(A, read_input()).
|
|
|
|
solve(['1'], D) ->
|
|
io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
|
|
solve(1, D) ->
|
|
solution1(D);
|
|
solve(['2'], D) ->
|
|
io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
|
|
solve(2, D) ->
|
|
solution2(D).
|
|
|
|
read_input() ->
|
|
{ok, IO} = file:open("input.txt", 'read'),
|
|
Data = read_input(IO),
|
|
file:close(IO),
|
|
Data.
|
|
|
|
read_input(IO) ->
|
|
read_line(IO).
|
|
|
|
read_line(IO) ->
|
|
case file:read_line(IO) of
|
|
'eof' -> 'eof';
|
|
{ok, Line} -> parse_line(Line)
|
|
end.
|
|
|
|
parse_line(Line) ->
|
|
Points = string:tokens(Line, " ,->\n"),
|
|
parse_line([list_to_integer(X) || X <- Points], [{0,0},{1,0},{2,0},{3,0},{4,0},{5,0},{6,0},{7,0},{8,0}]).
|
|
|
|
parse_line([], Acc) ->
|
|
io:format("input: ~p~n", [Acc]),
|
|
Acc;
|
|
parse_line([H|T], Acc) ->
|
|
{A, V} = lists:keyfind(H, 1, Acc),
|
|
parse_line(T, lists:keyreplace(H, 1, Acc, {A, V + 1})).
|
|
|
|
solution1(Input) ->
|
|
Fish = days(Input, 80),
|
|
io:format("OUT: ~p~n", [Fish]),
|
|
lists:foldl(fun({_A, V}, Acc) -> Acc + V end, 0, Fish).
|
|
solution2(Input) ->
|
|
Fish = days(Input, 256),
|
|
io:format("OUT: ~p~n", [Fish]),
|
|
lists:foldl(fun({_A, V}, Acc) -> Acc + V end, 0, Fish).
|
|
days(Input, 0) ->
|
|
Input;
|
|
days(Input, Count) ->
|
|
New =
|
|
lists:foldl(fun({A, V}, AccIn) ->
|
|
case A of
|
|
0 ->
|
|
{7, V1} = lists:keyfind(7, 1, Input),
|
|
AccIn ++ [{6, V + V1},{8, V}];
|
|
7 -> AccIn;
|
|
_ -> AccIn ++ [{A-1, V}]
|
|
end
|
|
end, [], Input),
|
|
days(New, Count -1).
|