How to replace random parts of string with random keys from array?

655 views Asked by At

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!

1

There are 1 answers

0
Nina Scholz On BEST ANSWER

You could split the string for an array and update at a special index and join the array for a new string.

function replace(string) {
    var array = string.split(''),
        i = Math.floor(Math.random() * array.length);

    array[i] = String.fromCharCode(array[i].charCodeAt(0) + 2 * Math.floor(Math.random() * 2) - 1);
    return array.join('');
}

console.log(replace('123456abcdef'));