Skip to content

Instantly share code, notes, and snippets.

@jackdreilly
Created September 19, 2011 18:13
Show Gist options
  • Save jackdreilly/1227157 to your computer and use it in GitHub Desktop.
Save jackdreilly/1227157 to your computer and use it in GitHub Desktop.
(def punc-regex #"\p{P}")
(defn wordify [s]
(map #(clojure.contrib.string/replace-re punc-regex "" (clojure.contrib.string/lower-case %1)) (.split s " ")))
(defn collect [pairs]
(loop [remPairs pairs
dict {}]
(if (empty? remPairs)
(seq dict)
(let [key (first (first remPairs))
val (last (first remPairs))]
(if (contains? dict key)
(recur (rest remPairs)
(assoc dict key
(cons val (get dict key ))))
(recur (rest remPairs) (assoc dict key [val])))))))
(defn map-reduce [coll mapper reducer]
(map
(fn [pair]
[(first pair)
(reduce reducer [] (last pair))
])
(collect (map mapper coll))))
(defn reducer [rv cv]
(if (some #{cv} rv)
rv
(cons cv rv)))
(defn mapper [word]
[(apply str (sort word)) word])
(defn anagrams
"find all anagrams in sentence"
[sentence]
(filter #(> (count %1) 1) (map last (map-reduce (wordify sentence) mapper reducer))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment