Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pbadenski/367455 to your computer and use it in GitHub Desktop.
Save pbadenski/367455 to your computer and use it in GitHub Desktop.
Playing with Genetic Algorithms
(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