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