target = "Juliet is the female protagonist and one of two title characters in William Shakespeare's romantic love tragedy Romeo and Juliet, the other being Romeo.".toUpperCase();
function R(n) { return Math.floor(n*Math.random()); }
function getChar() { return chars[R(chars.length)]; }
function getRandomString(){ var string = ""; for (var x = 0;x<target.length;x++){ string+=getChar(); } return string; }
function mutateString(s){ var t = s.split(""); for (var x=0;x<t.length;x++) if (Math.random() < mutationRate) t[x]=getChar(); return t.join(""); }
function fitness(str){ //number of matches var score = 0; for (var x = 0;x<target.length;x++){ if (str[x]==target[x]){ score++; } } return score; }
function init(){ for (var x=0;x<size;x++) population.push({str:getRandomString()}); }
function main(){ init(); var beststring; while (true){ population.forEach(function (y) { y.fitness = fitness(y.str); }); population.sort(function (a,b) { return b.fitness-a.fitness; }); beststring = population[0]; //console.log(population); console.log(beststring.str + "; generation: "+generation+" fitness: "+beststring.fitness); if (beststring.str == target) return; population = [beststring]; for (var x=1;x<size;x++) population.push({str:mutateString(beststring.str)}); generation++; } }
var population = []; var size = 50; var generation = 0; var mutationRate = 0.05; main();
Name:
Anonymous2019-04-28 5:05
>>7 Its kinda primitive for a genetic algorithm, its just randomizes letters and compares them to a fixed string, so eventually it just stumbles on correct letters. I bet however Mentifex would claim this is AI-built literature and artificial Shakespeare-in-a-box.