Last active
December 19, 2015 15:39
-
-
Save t-ob/5978186 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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 tob-guess-target [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