Created
June 6, 2011 10:09
-
-
Save pepijndevos/1010027 to your computer and use it in GitHub Desktop.
Find a word that spells your phone number
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
(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