Last active
December 23, 2015 23:59
-
-
Save mapkyca/6713698 to your computer and use it in GitHub Desktop.
A rough implementation of https://en.wikipedia.org/wiki/Weasel_program, experimenting with a simple genetic algorithm.
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
<?php | |
/** | |
* Genetic algorithm test. | |
* This is basically a rough implementation of the Weasel program | |
* https://en.wikipedia.org/wiki/Weasel_program | |
*/ | |
$ascii = "abcdefghijklmnopqrstuvwxyz "; // Ascii characters | |
$string_match = "dance then wherever you may be i am the lord of the dance said he"; // String we're looking for | |
$string_match = strtolower($string_match); | |
/** Generate a random string */ | |
function random_string($length) { | |
global $ascii; | |
$s = ""; | |
for ($n=0; $n < $length; $n++) | |
$s.= strtolower($ascii[rand(0,26)]); | |
return $s; | |
} | |
/** Mutate a given string */ | |
function random_string_from_src($string) { | |
global $ascii; | |
for ($n=0; $n<strlen($string); $n++) { | |
if (rand(0,19)==0) $string[$n] = $ascii[rand(0, 26)]; | |
} | |
return $string; | |
} | |
/** Score a string against it's target */ | |
function get_score($string, $target) { | |
$score = 0; | |
for ($n =0; $n < strlen($string); $n++) | |
if ($string[$n] == $target[$n]) $score ++; | |
return $score; | |
} | |
/** Mutate a string, produce children and pick the best one */ | |
function BREED($string) { | |
global $string_match; | |
$best = $string; | |
$best_score = get_score($string, $string_match); | |
for ($n = 0; $n < 100; $n++) | |
{ | |
$v = random_string_from_src($string); | |
if (get_score($v, $string_match)>=$best_score) { | |
$best = $v; | |
$best_score = get_score($v, $string_match); | |
} | |
} | |
return $best; | |
} | |
$cnt = 0; | |
$v = random_string(strlen($string_match)); | |
do { | |
$v = BREED($v); | |
$score = get_score($v, $string_match); | |
echo "Generation $cnt: $v ($score) \n"; | |
$cnt ++; | |
} while($score < strlen($string_match)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment