Skip to content

Instantly share code, notes, and snippets.

@mrw34
Forked from t-ob/west.clj
Last active December 19, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrw34/6016139 to your computer and use it in GitHub Desktop.
Save mrw34/6016139 to your computer and use it in GitHub Desktop.
(ns genetic.core)
(def letters
(conj (map (comp char
(partial + 97))
(range 26))
\space))
(defn random-string [source]
(let [length (count source)]
(apply str
(repeatedly length
(fn []
(rand-nth source))))))
(def letter-val-map
(into {}
(map vector
letters
(range))))
(defn char-diff [x y]
(Math/abs (- (letter-val-map x)
(letter-val-map y))))
(defn string-distance [s1 s2]
(reduce + (map char-diff s1 s2)))
(defn mutate-string [s]
(let [n (rand-int (count s))
[l [x & r]] (split-at n s)]
(apply str (concat l [(rand-nth letters)] r))))
(defn genetic-iteration [target seed]
(println seed)
(first (first (sort-by last
(for [s (map mutate-string (repeat 50 seed))]
[s (string-distance s target)])))))
(defn guess-target [iterations target]
(nth (iterate (partial genetic-iteration target) (random-string target))
iterations))
(defn -main [target]
(first (drop-while (fn [s]
(not= s target))
(iterate (partial genetic-iteration target) (random-string target)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment