Given a word and a list of possible anagrams, select the correct sublist.
Given "listen"
and a list of candidates like "enlists" "google" "inlets" "banana"
the program should return a list containing
"inlets"
.
Inspired by the Extreme Startup game https://github.com/rchatley/extreme_startup
It's possible to submit an incomplete solution so you can see how others have completed the exercise.
(ns anagram-test
(:require [clojure.test :refer [deftest is]]
anagram))
(deftest no-matches
(is (= []
(anagram/anagrams-for "diaper" ["hello" "world" "zombies" "pants"]))))
(deftest detect-simple-anagram
(is (= ["tan"] (anagram/anagrams-for "ant" ["tan" "stand" "at"]))))
(deftest does-not-confuse-different-duplicates
(is (= [] (anagram/anagrams-for "galea" ["eagle"]))))
(deftest eliminate-anagram-subsets
(is (= [] (anagram/anagrams-for "good" ["dog" "goody"]))))
(deftest detect-anagram
(is (= ["inlets"]
(let [coll ["enlists" "google" "inlets" "banana"]]
(anagram/anagrams-for "listen" coll)))))
(deftest multiple-anagrams
(is (= ["gallery" "regally" "largely"]
(let [coll ["gallery" "ballerina" "regally"
"clergy" "largely" "leading"]]
(anagram/anagrams-for "allergy" coll)))))
(deftest case-insensitive-anagrams
(is (= ["Carthorse"]
(let [coll ["cashregister" "Carthorse" "radishes"]]
(anagram/anagrams-for "Orchestra" coll)))))
(deftest word-is-not-own-anagram
(is (= [] (anagram/anagrams-for "banana" ["banana"]))))
(deftest capital-word-is-not-own-anagram
(is (= [] (anagram/anagrams-for "BANANA" ["banana"]))))
(ns anagram)
(defn count-capital-letters [word]
(count (clojure.string/replace word #"[a-z]+" "")))
(defn anagram? [word candidate]
(and
(not= word candidate)
(= (sort (clojure.string/lower-case word)) (sort (clojure.string/lower-case candidate)))
(= (count-capital-letters word) (count-capital-letters candidate))))
(defn anagrams-for
[word anagram-candidates]
(filter (partial anagram? word) anagram-candidates))
A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.
Here are some questions to help you reflect on this solution and learn the most from it.
Level up your programming skills with 3,449 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors. Exercism is 100% free forever.
Sign up Learn More
Community comments
What is counting the capital letters supposed to accomplish? You do not need this for the general solution. If this passes the tests, probably the test cases should be extended. Do you realize you are lower-casing and sorting the base word anew for each candidate? This is not very efficient. Can you refactor so you need to sort only once? Helper functions should be private (defn-) to hide implementation details.