Last active
June 12, 2016 21:38
-
-
Save stockwellb/21a7850e0c49b63c2ae2d96c99bec225 to your computer and use it in GitHub Desktop.
Find a sublist of anagrams, for a word, in a list of words
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Anagram do | |
def match(word,words) do | |
Enum.filter(words, fn(w) -> | |
source = String.downcase(word) | |
compare = String.downcase(w) | |
if source === compare do | |
false | |
else | |
a = to_char_list(source) |> Enum.sort | |
b = to_char_list(compare) |> Enum.sort | |
a == b | |
end | |
end) | |
end | |
end | |
ExUnit.start | |
defmodule AnagramTest do | |
use ExUnit.Case, async: true | |
test "no matches" do | |
matches = Anagram.match "diaper", ["hello", "world", "zombies", "pants"] | |
assert matches == [] | |
end | |
test "detect simple anagram" do | |
matches = Anagram.match "ant", ["tan", "stand", "at"] | |
assert matches == ["tan"] | |
end | |
test "detect multiple anagrams" do | |
matches = Anagram.match "master", ["stream", "pigeon", "maters"] | |
assert matches == ["stream", "maters"] | |
end | |
test "do not detect anagram subsets" do | |
matches = Anagram.match "good", ~w(dog goody) | |
assert matches == [] | |
end | |
test "detect anagram" do | |
matches = Anagram.match "listen", ~w(enlists google inlets banana) | |
assert matches == ["inlets"] | |
end | |
test "multiple anagrams" do | |
matches = Anagram.match "allergy", ~w(gallery ballerina regally clergy largely leading) | |
assert matches == ["gallery", "regally", "largely"] | |
end | |
test "anagrams must use all letters exactly once" do | |
matches = Anagram.match "patter", ["tapper"] | |
assert matches == [] | |
end | |
test "detect anagrams with case-insensitive subject" do | |
matches = Anagram.match "Orchestra", ~w(cashregister carthorse radishes) | |
assert matches == ["carthorse"] | |
end | |
test "detect anagrams with case-insensitive candidate" do | |
matches = Anagram.match "orchestra", ~w(cashregister Carthorse radishes) | |
assert matches == ["Carthorse"] | |
end | |
test "anagrams must not be the source word" do | |
matches = Anagram.match "corn", ["corn", "dark", "Corn", "rank", "CORN", "cron", "park"] | |
assert matches == ["cron"] | |
end | |
test "do not detect words based on checksum" do | |
matches = Anagram.match "mass", ["last"] | |
assert matches == [] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment