Sunday, January 22, 2012

Some 4Clojure Problems

  • The Anagram Finder Problem :  Write a function which finds all the anagrams in a vector of words. A word x is an anagram of word y if all the letters in x can be rearranged in a different order to form y. Your function should return a set of sets, where each sub-set is a group of words which are anagrams of each other. Each sub-set should have at least two words. Words without any anagrams should not be included in the result.
          There is a Clojure function called group-by, which partially addresses this problem. Noting that two   words   are anagrams iff upon sorting their values are the same, we can group the collection by the sorted word being the key. This puts the anagrams close to each other as values. After that point, a bit of massaging gives us the result we seek:



(defn anagram-finder [x]
  ( apply hash-set 
          (filter #(> (count %) 1)
                  (map #(apply hash-set (val %))(group-by sort x))) ))








No comments:

Post a Comment