]> fbox.kageds.com Git - adventofcode.git/blob - day6/day6.erl
Create 6.py
[adventofcode.git] / day6 / day6.erl
1 %% to compile: erlc day3A.erl
2 %% to run: erl -noshell -s day5 solve
3 %%
4 -module(day6).
5
6 -export ([solve/0, solve/1, solve/2]).
7 -export ([read_input/0]).
8
9 solve() ->
10 solve(['1']),
11 solve(['2']),
12 init:stop().
13
14 solve(A) ->
15 solve(A, read_input()).
16
17 solve(['1'], D) ->
18 io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
19 solve(1, D) ->
20 solution1(D);
21 solve(['2'], D) ->
22 io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
23 solve(2, D) ->
24 solution2(D).
25
26 read_input() ->
27 {ok, IO} = file:open("input.txt", 'read'),
28 Data = read_input(IO),
29 file:close(IO),
30 Data.
31
32 read_input(IO) ->
33 read_line(IO).
34
35 read_line(IO) ->
36 case file:read_line(IO) of
37 'eof' -> 'eof';
38 {ok, Line} -> parse_line(Line)
39 end.
40
41 parse_line(Line) ->
42 Points = string:tokens(Line, " ,->\n"),
43 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}]).
44
45 parse_line([], Acc) ->
46 io:format("input: ~p~n", [Acc]),
47 Acc;
48 parse_line([H|T], Acc) ->
49 {A, V} = lists:keyfind(H, 1, Acc),
50 parse_line(T, lists:keyreplace(H, 1, Acc, {A, V + 1})).
51
52 solution1(Input) ->
53 Fish = days(Input, 80),
54 io:format("OUT: ~p~n", [Fish]),
55 lists:foldl(fun({_A, V}, Acc) -> Acc + V end, 0, Fish).
56 solution2(Input) ->
57 Fish = days(Input, 256),
58 io:format("OUT: ~p~n", [Fish]),
59 lists:foldl(fun({_A, V}, Acc) -> Acc + V end, 0, Fish).
60 days(Input, 0) ->
61 Input;
62 days(Input, Count) ->
63 New =
64 lists:foldl(fun({A, V}, AccIn) ->
65 case A of
66 0 ->
67 {7, V1} = lists:keyfind(7, 1, Input),
68 AccIn ++ [{6, V + V1},{8, V}];
69 7 -> AccIn;
70 _ -> AccIn ++ [{A-1, V}]
71 end
72 end, [], Input),
73 days(New, Count -1).