Skip to content

Instantly share code, notes, and snippets.

@draegtun
Last active Apr 17, 2020
Embed
What would you like to do?
-module(dp383).
-export([same_necklace/2, repeats/1, bonus2/0, test_examples/0]).
%
% see - https://www.reddit.com/r/dailyprogrammer/comments/ffxabb/20200309_challenge_383_easy_necklace_matching/
same_necklace(A, B) when length(A) =/= length(B) -> false;
same_necklace(A, B) ->
case string:find(A ++ A, B) of
nomatch -> false;
_ -> true
end.
%%
%% Bonus 1
repeats("") -> 1;
repeats(S) -> repeats(S ++ S, S, 0).
repeats(A, B, Count) ->
case string:find(tl(A), B) of
nomatch -> Count;
Match -> repeats(Match, B, Count + 1)
end.
%%
%% Bonus 2
readlines(File) ->
{ok, Data} = file:read_file(File),
binary:split(Data, [<<"\r\n">>], [global]).
make_dict(Words) -> loop_words(Words, #{}).
loop_words([], Dict) -> Dict;
loop_words([H|T], Dict) ->
W = binary_to_list(H),
Lookup = lists:sort(W),
loop_words(T, maps:update_with(Lookup, fun(V) -> [W | V] end, [W], Dict)).
four_necklaces([]) -> [];
four_necklaces([H|_]) when length(H) < 4 -> [];
four_necklaces([H|T]) ->
{Matched, NotMatched} = lists:partition(fun(S) -> same_necklace(S, H) end, T),
case length(Matched) of
3 -> Matched ++ [H];
_ -> four_necklaces(NotMatched)
end.
bonus2() ->
File = "enable1.txt",
Dict = make_dict(readlines(File)),
Possibles = maps:values(Dict),
io:format("~p~n", [loop_bonus2(Possibles)]).
loop_bonus2([]) -> exhausted;
loop_bonus2([H|T]) when length(H) >= 4 ->
case four_necklaces(H) of
[] -> loop_bonus2(T);
Necklaces -> Necklaces
end;
loop_bonus2([_|T]) -> loop_bonus2(T).
%% tests
test_examples() ->
[
same_necklace("nicole", "icolen") =:= true,
same_necklace("nicole", "lenico") =:= true,
same_necklace("nicole", "coneli") =:= false,
same_necklace("aabaaaaabaab", "aabaabaabaaa") =:= true,
same_necklace("abc", "cba") =:= false,
same_necklace("xxyyy", "xxxyy") =:= false,
same_necklace("xyxxz", "xxyxz") =:= false,
same_necklace("x", "x") =:= true,
same_necklace("x", "xx") =:= false,
same_necklace("x", "") =:= false,
same_necklace("", "") =:= true,
repeats("abc") =:= 1,
repeats("abcabcabc") =:= 3,
repeats("abcabcabcx") =:= 1,
repeats("aaaaaa") =:= 6,
repeats("a") =:= 1,
repeats("") =:= 1
].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment