我正在用 Lua 编写一个非常简单的程序,以了解有关遗传编程的更多信息。下面是一个 mutate 函数,用于转到树中的编号节点 (nodeNum
) (pop
),并且可以:将 add 与 sub 交换(或反之亦然)或替换节点的随机数为 1-100。
local count = 0
function mutate(pop, nodeNum)
for k,v in ipairs(pop) do
if type(v) == "table" then
mutate(v, nodeNum)
else
count = count + 1
end
if count == nodeNum and k == 1 then -- correct node
if type(v) == "function" then
if v == add then
pop[k] = sub
else
pop[k] = add
end
else
pop[k] = math.random(100)
end
end
end
end
我的问题是count
。调用这个函数很尴尬,因为每次都必须重置 count
:
-- mutate the first 3 elements in program tree t
mutate(t,1)
count = 0
mutate(t, 2)
count = 0
mutate(t, 3)
我尝试过使用 do ... end
的变体,例如:
do
local count
function mutate(pop, nodeNum)
if not count then
count = 0
...
end
我还尝试给 mutate 一个额外的参数 mutate(pop, nodeNum, count)
并用 mutate(t, 1, 0)
调用它,但我可以这两种方法都无法正常工作。
我可能错过了一些非常明显的东西,有人能看到更优雅的解决方案吗?
最佳答案
function mutate(pop, nodeNum, count)
count = count or 0
for k,v in ipairs(pop) do
if type(v) == "table" then
mutate(v, nodeNum, count)
else
count = count + 1
end
if count == nodeNum and k == 1 then -- correct node
if type(v) == "function" then
if v == add then
pop[k] = sub
else
pop[k] = add
end
else
pop[k] = math.random(100)
end
end
end
end
关于recursion - 重置递归 Lua 函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12231855/