Permalink
Browse files

Get valid next words

  • Loading branch information...
grahamrhay committed Dec 30, 2018
1 parent 3afdf19 commit 8101d8cadcd97ac788f4fb7ffd3395f35b0a101a
Showing with 28 additions and 7 deletions.
  1. +10 −3 src/word_chains.erl
  2. +18 −4 test/prop_word_chains.erl
@@ -1,10 +1,17 @@
-module(word_chains).

-export([word_list/0, next_word/2]).
-export([word_list/0, next_words/1, get_word_distance/2]).

word_list() ->
{ok, Data} = file:read_file("words.txt"),
lists:map(fun(W) -> binary_to_list(W) end, binary:split(Data, [<<"\n">>], [global])).

next_word(_FirstWord, LastWord) ->
LastWord.
next_words(FirstWord) ->
WordList = word_list(),
SameLengthWords = lists:filter(fun(W) -> length(W) =:= length(FirstWord) end, WordList),
WordDistances = lists:map(fun(W) -> {W, get_word_distance(W, FirstWord)} end, SameLengthWords),
lists:map(fun({Word, _}) -> Word end, lists:filter(fun({_, Distance}) -> Distance =:= 1 end, WordDistances)).

get_word_distance(Word1, Word2) ->
Differences = lists:zipwith(fun(X, Y) -> case X =:= Y of true -> 0; false -> 1 end end, Word1, Word2),
lists:foldl(fun(D, Acc) -> Acc + D end, 0, Differences).
@@ -3,13 +3,15 @@
-include_lib("proper/include/proper.hrl").
-include_lib("eunit/include/eunit.hrl").

prop_next_word_should_be_new() ->
prop_next_words_should_be_near() ->
?FORALL({FirstWord, LastWord}, valid_words(),
begin
io:format("First word: ~p, Last word: ~p", [FirstWord, LastWord]),
NextWord = word_chains:next_word(FirstWord, LastWord),
io:format("Next word: ~p", [NextWord]),
NextWord =/= FirstWord
NextWords = word_chains:next_words(FirstWord),
io:format("Next words: ~p", [NextWords]),
InvalidWords = lists:filter(fun(W) -> word_chains:get_word_distance(W, FirstWord) =/= 1 end, NextWords),
io:format("Invalid words: ~p", [InvalidWords]),
length(InvalidWords) =:= 0
end).

valid_words() ->
@@ -38,3 +40,15 @@ word_list_last_word_test() ->
WordList = word_chains:word_list(),
LastWord = lists:last(WordList),
?assertEqual(LastWord, "zzzs").

get_word_distance_same_word_test() ->
WordDistance = word_chains:get_word_distance("cat", "cat"),
?assertEqual(0, WordDistance).

get_word_distance_near_word_test() ->
WordDistance = word_chains:get_word_distance("cat", "cot"),
?assertEqual(1, WordDistance).

get_word_distance_far_word_test() ->
WordDistance = word_chains:get_word_distance("cat", "dog"),
?assertEqual(3, WordDistance).

0 comments on commit 8101d8c

Please sign in to comment.