Last active
July 3, 2023 08:30
-
-
Save ppsdatta/792428b6c9ee76b4bd0e5ea44e733f41 to your computer and use it in GitHub Desktop.
Weasel code in Common Lisp
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
(defconstant target "ME THINKS IT IS LIKE A WEASEL") | |
(defun rand-letter () | |
(let ((r (random 27))) | |
(if (= r 26) | |
#\space | |
(code-char (+ (char-code #\A) r))))) | |
(defun rand-string (n) | |
(coerce (loop for i from 1 to n | |
collect (rand-letter)) | |
'string)) | |
(defun chance-mutate (s) | |
(let ((l (coerce s 'list))) | |
(coerce | |
(loop for i in l | |
collect (let ((r (random 100))) | |
(if (and (>= r 42) | |
(<= r 52)) | |
(rand-letter) | |
i))) | |
'string))) | |
(defun create-population (parent n) | |
(loop for i from 1 to n | |
collect (chance-mutate parent))) | |
(defun score (s target-s) | |
(reduce #'+ | |
(loop for i in (coerce s 'list) | |
for j in (coerce target-s 'list) | |
collect (abs (- (char-code i) | |
(char-code j)))) | |
:start 0)) | |
(defun find-survivor (pop target-s) | |
(second | |
(first | |
(sort | |
(loop for i in pop | |
collect (list | |
(score i target-s) | |
i)) | |
#'(lambda (p q) (< (first p) (first q))))))) | |
(defun generations (start | |
stop-n | |
target-s | |
&key (population 1000)) | |
(do ((p start (find-survivor | |
(create-population p population) | |
target-s)) | |
(i 1 (+ i 1))) | |
((or (> i stop-n) | |
(string= p target-s)) | |
(return p)) | |
(format t | |
"Gen ~A - ~A~%" | |
i | |
p))) | |
(defun weasels (target-s &key (n 200)) | |
(generations (rand-string (length target-s)) | |
n | |
target-s)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment