Skip to content

Instantly share code, notes, and snippets.

@CaseyLeask
Created November 1, 2016 08:31
Show Gist options
  • Save CaseyLeask/83f273cf55865a114156cf0ded036c95 to your computer and use it in GitHub Desktop.
Save CaseyLeask/83f273cf55865a114156cf0ded036c95 to your computer and use it in GitHub Desktop.
-module(solution).
-export([main/0]).
main() ->
printContacts(sortContacts(filterContacts(createContacts(readAll())))).
readAll() ->
readAll([], io:get_chars("", 4096)).
readAll(In, eof) ->
[StringN|Lines] = string:tokens(lists:flatten(lists:reverse(In)), "\n"),
{list_to_integer(StringN), Lines};
readAll(In, Data) ->
readAll([Data|In], io:get_chars("", 4096)).
createContacts({N, Entries}) ->
createContacts({N, Entries}, []).
createContacts({0, _Entries}, PhoneBook) ->
PhoneBook;
createContacts({N, [Entry|Lines]}, PhoneBook) ->
[Key, Value] = string:tokens(Entry, " "),
createContacts({N-1, Lines}, lists:append([{Key, Value}], PhoneBook)).
filterContacts(Contacts) ->
filterContacts(Contacts, []).
filterContacts([], Out) ->
Out;
filterContacts([{Firstname, Email} | In], Out) ->
case re:run(Email, "@gmail.com$") of
{match, _} -> filterContacts(In, [Firstname | Out]);
nomatch -> filterContacts(In, Out)
end.
sortContacts(Contacts) ->
lists:sort(Contacts).
printContacts(Contacts) ->
lists:foreach(fun(Contact) -> io:fwrite("~s~n", [Contact]) end, Contacts).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment