Skip to content

Instantly share code, notes, and snippets.

@jedisct1
Created May 4, 2011 16:07
Show Gist options
  • Save jedisct1/955485 to your computer and use it in GitHub Desktop.
Save jedisct1/955485 to your computer and use it in GitHub Desktop.
My modest attempt at solving the causes.com puzzle
-module(causes).
-export([causes/1]).
leven1(Word, Word) -> not_friends;
leven1(Left, Right) when length(Left) == length(Right) ->
leven1_subst(Left, Right, friends);
leven1(Left, Right) -> leven1_insert(Left, Right).
leven1_subst([], [], _Acc) -> friends;
leven1_subst([H|TLeft], [H|TRight], Acc) ->
leven1_subst(TLeft, TRight, Acc);
leven1_subst([_|TLeft], [_|TRight], friends) ->
leven1_subst(TLeft, TRight, not_friends);
leven1_subst(_, _, not_friends) -> not_friends.
leven1_insert([H|TLeft], [H|TRight]) -> leven1_insert(TLeft, TRight);
leven1_insert([_|T], T) -> friends;
leven1_insert(T, [_|T]) -> friends;
leven1_insert(_, _) -> not_friends.
friends(Dict, RefWord) ->
Pred = fun(OtherWord) -> leven1(RefWord, OtherWord) == friends end,
sets:from_list(lists:filter(Pred, Dict)).
friends_of_friends(_Dict, Friends, AlreadyKnown, 0) ->
sets:union(AlreadyKnown, Friends);
friends_of_friends(Dict, Friends, AlreadyKnown, N) ->
Pred = fun(Friend, AccIn) -> sets:union(AccIn, friends(Dict, Friend)) end,
FriendsOfFriends = sets:fold(Pred, sets:new(), Friends),
friends_of_friends(Dict, sets:subtract(FriendsOfFriends, AlreadyKnown),
sets:union(AlreadyKnown, Friends), N - 1).
readfile(FileName) ->
{ok, Binary} = file:read_file(FileName),
string:tokens(binary_to_list(Binary), "\n").
causes(Depth) ->
Dict = readfile("/tmp/word.list"),
RefList = sets:from_list(["causes"]),
sets:to_list(friends_of_friends(Dict, RefList, RefList, Depth)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment