【发布时间】:2018-02-07 22:28:37
【问题描述】:
下面的代码正在替换字符串中的随机字符,我试图让它从单词数组中替换部分字符串。
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
任何帮助将不胜感激!
【问题讨论】:
标签: javascript genetic-algorithm genetic-programming