Skip to content

Instantly share code, notes, and snippets.

@hiphamster
Created March 1, 2018 23:03
Show Gist options
  • Save hiphamster/336bc156be50904d8f478e4d1854d178 to your computer and use it in GitHub Desktop.
Save hiphamster/336bc156be50904d8f478e4d1854d178 to your computer and use it in GitHub Desktop.
sample clojure code
(ns anagram
(:gen-class))
(defn anagrams-for
"select anagrams from the list of words"
([] "nothing")
([word words]
(let [ word-chars (frequencies (for [c (clojure.string/lower-case word)] c))
anagram-wannabe-map (zipmap (map clojure.string/lower-case words)
(map (comp frequencies clojure.string/lower-case) words))
; { char frequencies => list of words }
anagram-wannabe-map-inverted (apply merge-with (comp flatten list)
(for
[kv (map reverse
(seq (zipmap words
(map (comp frequencies clojure.string/lower-case) words))))]
{(first kv) (last kv)}))
]
(into []
(filter #(not (nil? %))
(map #(if (nil? (re-matches (re-pattern (str "(?i)" %)) word)) %)
(flatten
(distinct
(for [anagram-wannabe
(for [a-word words] (anagram-wannabe-map (clojure.string/lower-case a-word)))]
(if (= anagram-wannabe word-chars)
(anagram-wannabe-map-inverted anagram-wannabe)
)
)
)
)
)
)
)
)
)
)
(defn -main
([])
([& args]
(let [args (map clojure.string/lower-case args)
word (first args)
words (dedupe (rest args))
]
(anagrams-for word words)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment