Evolutionary algorithm: Difference between revisions

Line 482:
=={{header|Clojure}}==
Define the evolution parameters (values here per Wikipedia article), with a couple of problem constants.
<lang lispclojure>(def c 100) ;number of children in each generation
(def p 0.05) ;mutation probability
 
Line 489:
(def alphabet " ABCDEFGHIJLKLMNOPQRSTUVWXYZ")</lang>
Now the major functions. ''fitness'' simply counts the number of characters matching the target.
<lang lispclojure>(defn fitness [s] (count (filter true? (map = s target))))
(defn perfectly-fit? [s] (= (fitness s) (count target)))
 
Line 495:
(defn mutate [s] (map #(if (< (rand) p) (randc) %) s))</lang>
Finally evolve. At each generation, print the generation number, the parent, and the parent's fitness.
<lang lispclojure>(loop [generation 1, parent (take (count target) (repeatedly randc))]
(println generation, (apply str parent), (fitness parent))
(if-not (perfectly-fit? parent)
Anonymous user