Skip to content

Instantly share code, notes, and snippets.

@bjorng
Created November 29, 2021 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjorng/377c950880c7411ce21d7fd8625ce839 to your computer and use it in GitHub Desktop.
Save bjorng/377c950880c7411ce21d7fd8625ce839 to your computer and use it in GitHub Desktop.
Solution for Advent of Code 2002 - Day 1
-module(aoc2020_day01).
-export([part1/0,part2/0]).
-include_lib("eunit/include/eunit.hrl").
%% Solve part 1 - expects the input to be in the file "input01.txt".
part1() ->
Input = parse_input(),
solve_part1(Input).
%% Solve part 2 - expects the input to be in the file "input01.txt".
part2() ->
Input = parse_input(),
solve_part2(Input).
parse_input() ->
Input = read_input("input01.txt"),
[list_to_integer(Line) || Line <- Input].
solve_part1(Integers) ->
Set = sets:from_list(Integers, [{version,2}]),
find_sum(Integers, Set, 2020).
solve_part2(Integers) ->
Set = sets:from_list(Integers, [{version,2}]),
solve_part2(Integers, Set).
solve_part2([Int|Integers], Set) ->
Other = 2020 - Int,
case find_sum(Integers, Set, Other) of
Product when is_integer(Product) ->
Product * Int;
none ->
solve_part2(Integers, Set)
end;
solve_part2([], _) ->
none.
find_sum([Int|Integers], Set, DesiredSum) ->
Other = DesiredSum - Int,
case sets:is_element(Other, Set) of
true -> Int * Other;
false -> find_sum(Integers, Set, DesiredSum)
end;
find_sum([], _, _) ->
none.
read_input(File) ->
{ok,Fd} = file:open(File, [read]),
Result = read_input_1(Fd),
file:close(Fd),
Result.
read_input_1(Fd) ->
case io:get_line(Fd, '') of
eof ->
[];
Line ->
[string:trim(Line)|read_input_1(Fd)]
end.
-ifdef(EUNIT).
part1_test() ->
?assertEqual(514579, solve_part1(example())).
part2_test() ->
?assertEqual(241861950, solve_part2(example())).
example() ->
[1721,
979,
366,
299,
675,
1456].
-endif.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment