Skip to content

Instantly share code, notes, and snippets.

@juanbono
Created December 5, 2019 01:24
Show Gist options
  • Save juanbono/63bd30ca940af9e072c30b941d8c8161 to your computer and use it in GitHub Desktop.
Save juanbono/63bd30ca940af9e072c30b941d8c8161 to your computer and use it in GitHub Desktop.
advent of code 2019 - day 4
-module(day4).
-define(INPUT_FILE, "src/day4/input.txt").
-export([part1/0, part2/0]).
%%====================================================================
%% Main functions
%%====================================================================
part1() ->
{Start, End} = read_range(?INPUT_FILE),
AllPasswords = [integer_to_list(N) || N <- lists:seq(Start, End)],
Passwords = lists:filter(fun is_valid_password1/1, AllPasswords),
length(Passwords).
part2() ->
{Start, End} = read_range(?INPUT_FILE),
AllPasswords = [integer_to_list(N) || N <- lists:seq(Start, End)],
Passwords = lists:filter(fun is_valid_password2/1, AllPasswords),
length(Passwords).
%%====================================================================
%% Internal functions
%%====================================================================
is_valid_password1(Pass) ->
is_non_decreasing(Pass) andalso has_double(Pass).
is_valid_password2(Pass) ->
is_non_decreasing(Pass) andalso has_double_strict(Pass).
is_non_decreasing(Pass) -> lists:sort(Pass) == Pass.
has_double([]) -> false;
has_double([A, A]) -> true;
has_double([A, A | _Rest]) -> true;
has_double([_H | T]) -> false orelse has_double(T).
has_double_strict(Pass) ->
EncodedPass = encode(Pass),
proplists:is_defined(2, EncodedPass).
%% run-length encoding
encode(List) ->
Counts = lists:foldr(
fun (Prev, [{Count, Prev} | Rest]) ->
[{Count + 1, Prev} | Rest];
(Current, Acc) ->
[{1, Current} | Acc]
end, [], List),
lists:flatten(Counts).
read_range(File) ->
{ok, Bin} = file:read_file(File),
FirstLine = hd(binary:split(Bin, <<"\n">>)),
[Start, End] = [binary_to_integer(N) || N <- string:lexemes(FirstLine, [$-])],
{Start, End}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment