考虑这个功能:
function generation(input_text, characters, target_text, mutation_rate, amount_offspring) {
var generationObject = [{string:"", score: 0}];
var evolved_string = "";
var best_offspring = {string:"", score: 0};
for(var i = 0; i <= amount_offspring; i++) {
evolved_string = evolve(input_text, characters, mutation_rate)
console.log("E= " + evolved_string);
generationObject.push({
string: evolved_string,
score: score(target_text, evolved_string)
});
console.log(generationObject[i]);
// if there are more then 2 elements in the object array.
Check if the current offspring has a higher score then the previous one.
If it does, its the best offspring
if (generationObject.length > 1) {
if (generationObject[i].score > best_offspring.score) {
best_offspring.string = generationObject[i].string;
best_offspring.score = generationObject[i].score;
}
}
// if there only is one offspring. Its the best, by defult.
else {
best_offspring.string = generationObject[i].string;
best_offspring.score = generationObject[i].score;
}
// increment generations
generations++;
return best_offspring.string;
}
此循环是较大程序http://pastebin.com/tRU1KYP7和http://pastebin.com/MDt3M2s5的一部分,它以字符串作为输入,复制字符串amount_offspring
次,同时改变其中一个字符。我的错误是它尝试通过执行evolved_string
将score
和generationObject
推送到.push()
数组。
似乎这样做会跳过generationObject[0]
。这是为什么?我可以使用任何其他方法添加到我的阵列吗? THX!
编辑: 在这里我做了一个控制台输出,这样你就可以更清楚地看到我的意思了!
functions.js:4 Input= xkt
functions.js:13 Evolved= xkr
functions.js:18 Object {string: "", score: 0}
functions.js:13 Evolved= xks
functions.js:18 Object {string: "xkr", score: 0}
functions.js:13 Evolved= xct
functions.js:18 Object {string: "xks", score: 0}
但是在这里你可以看到functions.js:18 Object {string: "", score: 0}
在第一次运行时是这样的。为什么呢?
答案 0 :(得分:2)
使用单个对象初始化数组:
var generationObject = [{string:"", score: 0}]; //use var generationObject = []; instead
您的溢出错误来自此处:
i <= amount_offspring; //should be i < amount_offspring, since you start at 0