Created
September 19, 2011 18:13
-
-
Save jackdreilly/1227157 to your computer and use it in GitHub Desktop.
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
(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