Created
April 15, 2010 18:22
-
-
Save pbadenski/367455 to your computer and use it in GitHub Desktop.
Playing with Genetic Algorithms
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
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
(fn gen-chromosome [] | |
(lazy-seq | |
(cons | |
(rand-int 2) | |
(gen-chromosome)))) | |
(defn random-individual [population] | |
(nth population (rand-int (count population)))) | |
(defn crossover [i1 i2] | |
(let [half-way (/ (count i1) 2)] | |
(map concat | |
(split-at half-way i1) | |
(split-at half-way i2)))) | |
(defn flip [i] (get {0 1, 1 0} i)) | |
(defn mutate-individual [individual] | |
(let [random-gene-pos (rand-int (dec (count individual)))] | |
(concat | |
(take random-gene-pos individual) | |
[(flip (nth individual (inc random-gene-pos)))] | |
(drop (inc random-gene-pos) individual)))) | |
(defn mutate [population] | |
(map | |
#((if (zero? (rand-int 100/10)) | |
mutate-individual | |
identity) %) | |
population)) | |
(defn breed [population] | |
(lazy-seq | |
(concat | |
(crossover | |
(random-individual population) | |
(random-individual population)) | |
(breed population)))) | |
(defn fit-func [individual] | |
(count | |
(filter | |
#(= % 1) | |
individual))) | |
(loop [ | |
population | |
(take 10 | |
(repeatedly | |
#(take 8 | |
(gen-chromosome)))) | |
time | |
10] | |
(if (zero? time) | |
population | |
(recur | |
(take 10 | |
(sort | |
#(> (fit-func %1) (fit-func %2)) | |
(concat | |
(mutate population) | |
(take 10 | |
(breed population))))) | |
(dec time)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment