【问题标题】:How to replace random parts of string with random keys from array?如何用数组中的随机键替换字符串的随机部分?
【发布时间】: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


    【解决方案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'));

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 2018-04-08
      • 2018-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多