1 %% to compile: erlc day8.erl
2 %% to run: erl -noshell -s day5 solve
6 -export ([solve/0, solve/1, solve/2]).
7 -export ([read_input/0]).
15 solve(A, read_input()).
18 io:format("The solution to ~p puzzle1 is: ~p~n", [?MODULE, solve(1, D)]);
22 io:format("The solution to ~p puzzle2 is: ~p~n", [?MODULE, solve(2, D)]);
27 {ok, IO} = file:open("input.txt", 'read'),
28 Data = read_input(IO),
35 read_input(IO, Input) ->
38 Line -> read_input(IO, lists:reverse([Line|Input]))
42 case file:read_line(IO) of
44 {ok, Line} -> parse_line(Line)
48 [string:tokens(X, " \n") || X <- string:split(Line, "|")].
51 lists:foldl(fun([_,X], Acc) -> count_unique(X, Acc) end, 0, Input).
54 solution2([[I|[O]]|T]) ->
55 [One] = find_length(2,I),
56 [Seven] = find_length(3,I),
57 [Four] = find_length(4,I),
58 [Eight] = find_length(7,I),
59 Three = find_three(find_length(5, I), One),
60 Nine = find_nine(find_length(6, I), Four),
61 [Five, Two] = find_five_and_two(find_length(5, I), Three, Four),
62 [Six, Zero] = find_six_and_zero(find_length(6, I), Nine, One),
63 Key = [{lists:sort(One), 1},{lists:sort(Two), 2},{lists:sort(Three), 3},{lists:sort(Four), 4},{lists:sort(Five), 5},{lists:sort(Six), 6},{lists:sort(Seven), 7},{lists:sort(Eight), 8},{lists:sort(Nine), 9}, {lists:sort(Zero), 0}],
64 [{_, A},{_,B},{_,C},{_,D}] = [lists:keyfind(lists:sort(X), 1, Key) || X <- O],
65 (A * 1000 + B * 100 + C * 10 + D) + solution2(T).
67 count_unique([], V) -> V;
68 count_unique([H|T], V) ->
69 count_unique(T, V + count(length(H))).
77 find_length(_Len, []) -> [];
78 find_length(Len, [H|T]) when length(H) == Len -> [H|find_length(Len, T)];
79 find_length(Len, [_H|T]) -> find_length(Len, T).
81 find_three([H|T], One) ->
82 case length(minus(H, One)) of
84 _ -> find_three(T, One)
87 find_nine([H|T], Four) ->
88 case length(minus(H, Four)) of
90 _ -> find_nine(T, Four)
93 find_five_and_two(Fives, Three, Four) ->
94 N = lists:delete(Three, Fives),
95 find_five_and_two(N, Four).
97 find_five_and_two([H,T], Four) ->
98 case length(minus(H, Four)) of
102 find_six_and_zero(Sixes, Nine, One) ->
103 N = lists:delete(Nine, Sixes),
104 find_six_and_zero(N, One).
106 find_six_and_zero([H,T], One) ->
107 case length(minus(H, One)) of
113 lists:foldl(fun(T, Acc) -> lists:delete(T, Acc) end, X, Y).