Skip to content

Instantly share code, notes, and snippets.

@pepijndevos
Created June 6, 2011 10:09
Show Gist options
  • Save pepijndevos/1010027 to your computer and use it in GitHub Desktop.
Save pepijndevos/1010027 to your computer and use it in GitHub Desktop.
Find a word that spells your phone number
(ns test
(require clojure.java.io
clojure.string))
(def *keys* {\2 #{\a \b \c}, \3 #{\d \e \f}, \4 #{\g \h \i}, \5 #{\j \k \l}, \6 #{\m \n \o}, \7 #{\p \q \r \s}, \8 #{\t \u \v}, \9 #{\w \x \y \z}})
(def *mapping* (into {} (mapcat (fn [[k v]] (map #(vector % k) v)) *keys*)))
(def *words* (line-seq (clojure.java.io/reader "/usr/share/dict/words")))
(defn build-trie [words f]
(into {}
(for [[prefix words] (group-by
(comp *mapping* f)
(map clojure.string/lower-case words))]
(if (nil? prefix)
[prefix (first words)]
[prefix
(build-trie words (comp f rest))]))))
(defn lookup [trie number]
(get-in trie (conj (vec number) nil)))
;user=> (def trie (time (build-trie *words* first)))
;"Elapsed time: 4112.297 msecs"
;#'user/trie
;user=> (time (lookup trie "227738"))
;"Elapsed time: 0.053 msecs"
;"barret"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment