2017-08-30 155 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'));