The code below is replacing random characters from the string, I am trying to make it replace parts of string from an array of words.
genetic.mutate = function(entity) {
function replaceAt(str, index, character) {
return str.substr(0, index) + character + str.substr(index+character.length);
}
// chromosomal drift
var i = Math.floor(Math.random()*entity.length)
console.log(replaceAt(entity, i, String.fromCharCode(entity.charCodeAt(i) + (Math.floor(Math.random()*2) ? 1 : -1))));
return replaceAt(entity, i, String.fromCharCode(entity.charCodeAt(i) + (Math.floor(Math.random()*2) ? 1 : -1)));
};
The entity is a string of random characters with a length of "solution" text field value. Mutate function is using "charCode" + math random to find characters closer to a solution, and later in the fitness function, it gives fitness points to the algorithm, if it close to a solution. How to change mutate function, so it would try random keys from a set of the array, that contain all the words from the solution?
Here is the demo
https://codepen.io/anon/pen/MvzZPj?editors=1000
Any help would be appreciated!
You could split the string for an array and update at a special index and join the array for a new string.