Last active
August 16, 2017 07:54
-
-
Save dorukcan/e2f5d7124f02832cd1cd to your computer and use it in GitHub Desktop.
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
var alphabet = "ABCDEFGHIJKLMONPQRSTUVWXYZ ", | |
target = "METHINKS IT IS LIKE A WEASEL", | |
i, score = 0, copies, gen = 0, child = ""; | |
String.prototype.replaceAt = function(index, character) { | |
return this.substr(0, index) + character + this.substr(index+1); | |
} | |
String.prototype.shuffle = function() { | |
var i = this.length, j, temp = this; | |
while ( --i ) { | |
j = generateRandom(i + 1); | |
temp = temp.replaceAt(i, temp[j]); | |
} | |
return temp; | |
} | |
String.prototype.makeMutations = function() { | |
var i, newChar, str = this; | |
for(i=0; i<str.length; i++){ | |
if( Math.floor(Math.random() * 100) < 5 ){ | |
newChar = alphabet[generateRandom(alphabet.length)]; | |
str = str.replaceAt(i, newChar); | |
} | |
} | |
return str; | |
} | |
String.prototype.calculateScore = function() { | |
var i, score=0, str = this; | |
for(i=0; i<str.length; i++){ | |
if(str[i] == target[i]){ | |
score++; | |
} | |
} | |
return score; | |
} | |
function generateRandom(max){ | |
return Math.floor(Math.random() * max) | |
} | |
//Start with a random string of 28 characters. | |
child = alphabet.shuffle() | |
copies = []; | |
for(i=0; i<100; i++){ | |
//For each character in each of the 100 copies, with a probability of 5%, replace (mutate) the character with a new random character. | |
child = child.makeMutations(); | |
//Make 100 copies of the string (reproduce). | |
copies.push(child); | |
//Compare each new string with the target string "METHINKS IT IS LIKE A WEASEL", and give each a score (the number of letters in the string that are correct and in the correct position). | |
console.log(i + ": " + child + " -- score: " + child.calculateScore()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment