2

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 Answer 1

2

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'));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.