2017-08-30 157 views
2

下面的代码是从字符串中替换随机字符,我试图使它从字数组中替换字符串的部分。如何用数组中的随机键替换字符串的随机部分?

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

实体是一个长度为“解决方案”文本字段值的随机字符串。变异函数使用“charCode”+数学随机查找更接近解的字符,稍后在适应度函数中,如果算法接近解,则它给出算法的健身点。如何更改mutate函数,所以它会尝试从一组数组中获取包含解决方案中所有单词的随机密钥?

这里是演示

https://codepen.io/anon/pen/MvzZPj?editors=1000

任何帮助,将不胜感激!

回答

1

您可以拆分数组的字符串并在特殊索引处进行更新并将数组连接到新字符串。

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