Created
April 1, 2012 00:19
-
-
Save bodil/2269966 to your computer and use it in GitHub Desktop.
Clojure solution for http://addagram.mytestbench.com/ with ~1s execution time.
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 addagram.core | |
(:use [clojure.test] | |
[clojure.java.io :only [reader]])) | |
(with-test | |
(defn sort-largest [l] | |
(sort-by #(- (count %)) l)) | |
(is (= ["blerk" "quux" "foo" "bar"] | |
(sort-largest ["foo" "quux" "bar" "blerk"])))) | |
(def words (delay (sort-largest (line-seq (reader "WORD.LST"))))) | |
(def anagram-map | |
(delay | |
(loop [d {} w @words] | |
(if (seq w) | |
(recur (assoc d (sort (first w)) (first w)) (rest w)) | |
d)))) | |
(defn first-anagram [word] (@anagram-map (sort word))) | |
(with-test | |
(defn drop-one [word] | |
(for [i (range (count word))] | |
(str (apply str (take i word)) | |
(apply str (drop (inc i) word))))) | |
(is (= '("hai" "oai" "ohi" "oha") (drop-one "ohai")))) | |
(defn addagram-reduction [word] | |
(first (filter string? (map first-anagram (drop-one word))))) | |
(defn addagram [word] | |
(loop [current word words ()] | |
(if (< (count current) 4) (conj words current) | |
(if-let [next (addagram-reduction current)] | |
(recur next (conj words current)) | |
nil)))) | |
(defn longest-addagram [] | |
(first (remove nil? (pmap addagram @words)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment