Looks like I’m a bit late to the party here
Some Erlang allowed?
First idea was to take each element and do the calculation to the rest of the list that comes after the element.
Quite easy for part 1:
-module(day1_1).
-export([run/0]).
run()->
process_list(load_file("day1input.txt")).
load_file(Filename)->
{ok, Binary} = file:read_file(Filename),
StringContent = unicode:characters_to_list(Binary),
[ element(1, string:to_integer(Substr)) || Substr <- string:tokens(StringContent, "\n")].
process_list([H | T])->
case process_sublist(H, T) of
notfound -> process_list(T);
{found, X, Y, Result} -> {X, Y, Result}
end;
process_list([])->
notfound.
process_sublist(Elem, [H | T]) ->
case is_solution(Elem, H) of
true -> {found, Elem, H, H*Elem};
false -> process_sublist(Elem, T)
end;
process_sublist(_, []) ->
notfound.
is_solution(X, Y) ->
X + Y =:= 2020.
but getting more complicated for part 2:
-module(day1_2).
-export([run/0]).
run()->
process_list(load_file("day1input.txt")).
load_file(Filename)->
{ok, Binary} = file:read_file(Filename),
StringContent = unicode:characters_to_list(Binary),
[ element(1, string:to_integer(Substr)) || Substr <- string:tokens(StringContent, "\n")].
process_list([H | T])->
case process_sublist(H, T) of
notfound -> process_list(T);
X -> X
end;
process_list([])->
notfound.
process_sublist(Elem, [H1 | T]) ->
case process_subsublist(Elem, H1, T) of
notfound -> process_sublist(Elem, T);
X -> X
end;
process_sublist(_, []) ->
notfound.
process_subsublist(Elem1, Elem2, [H | T])->
case is_solution(Elem1, Elem2, H) of
true -> {found, Elem1, Elem2, H, H*Elem1*Elem2};
false -> process_subsublist(Elem1, Elem2, T)
end;
process_subsublist(_,_, []) ->
notfound.
is_solution(X, Y, Z) ->
X + Y + Z =:= 2020.
After finishing that I thought it’s just too much code, and did the brute force one-liner
process_list(L)->
[{X, Y, X*Y} || X <- L, Y <- L, X + Y =:= 2020 ].