Skip to content

Instantly share code, notes, and snippets.

@dorukcan
Last active August 16, 2017 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dorukcan/e2f5d7124f02832cd1cd to your computer and use it in GitHub Desktop.
Save dorukcan/e2f5d7124f02832cd1cd to your computer and use it in GitHub Desktop.
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