Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created April 18, 2012 19:02
Show Gist options
  • Select an option

  • Save martintrojer/2415795 to your computer and use it in GitHub Desktop.

Select an option

Save martintrojer/2415795 to your computer and use it in GitHub Desktop.
Knuth Anagrams
(defn get-anagram-map
"map of words keyed by letter-sorted 'words' (which all anagrams share)"
[dict]
(reduce (fn [acc w]
(let [sw (apply str (sort w))]
(if-let [d (get acc sw)]
(assoc acc sw (conj d w))
(assoc acc sw (list w))))) {} dict))
(defn knuth-anagrams
"what words in a dictionary are anagrams?"
[dict]
(->> (get-anagram-map dict)
(filter #(> (count (second %)) 1))
(map second)))
(knuth-anagrams ["lander", "earth", "antsier", "heart", "asterin", "randel"])
(defn all-anagrams
"quickly find all anagrams given a dictionary and a word"
[dict word]
(let [am (get-anagram-map dict)
sw (apply str (sort word))]
(get am sw)))
(all-anagrams ["lander", "earth", "antsier", "heart", "asterin", "randel"]
"earth")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment