RosettaCodeData/Task/Evolutionary-algorithm/Common-Lisp/evolutionary-algorithm-2.lisp

24 lines
712 B
Common Lisp
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
(defun unfit (s1 s2)
(loop for a across s1
2026-02-01 16:33:20 -08:00
for b across s2 count(char/= a b)))
2023-07-01 11:58:00 -04:00
(defun mutate (str alp n) ; n: number of chars to mutate
(let ((out (copy-seq str)))
(dotimes (i n) (setf (char out (random (length str)))
2026-02-01 16:33:20 -08:00
(char alp (random (length alp)))))
2023-07-01 11:58:00 -04:00
out))
(defun evolve (changes alpha target)
(loop for gen from 1
2026-02-01 16:33:20 -08:00
with f2 with s2
with str = (mutate target alpha 100)
with fit = (unfit target str)
while (plusp fit) do
(setf s2 (mutate str alpha changes)
f2 (unfit target s2))
(when (> fit f2)
(setf str s2 fit f2)
(format t "~5d: ~a (~d)~%" gen str fit))))
2023-07-01 11:58:00 -04:00
(evolve 1 " ABCDEFGHIJKLMNOPQRSTUVWXYZ" "METHINKS IT IS LIKE A WEASEL")