Lua 3分交叉帮助开始

时间:2014-11-24 19:31:42

标签: lua genetic-algorithm genetic-programming

我想为遗传编程实现3点交叉,但我不知道该怎么做以及从哪里开始。

我的意见是:

a = {(first pair), (second pair), ... etc.} 

例如a = {(12345,67890), (09876,54321)}(这些是数字,而不是字符串)

输出:像这样:

示例:a_1 = {(12895), (67340)}也是数字。

感谢您的回复并抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

这是我使用大多数整数运算的整数k点交叉的快速实现。从这开始,您可以使用循环扩展它以交叉多对整数的染色体。

math.randomseed(111)
-- math.randomseed(os.time())

a = 12345
b = 67890
len = 5 -- number of digits

function split(mum, dad, len, base)
    local split = math.pow(base, math.random(len))
    local son = math.floor(dad / split) * split + mum % split
    local daughter = math.floor(mum / split) * split + dad % split
    return son, daughter
end

function kpoint(mum, dad, len, base, k)
    for i=1, k do
      mum, dad = split(mum, dad, len, base)
    end
    return mum, dad
end

s, d = kpoint(a, b, len, 10, 3) -- 3 point crossover in base 10
print(s) -- 67395
print(d) -- 12840

-- binary, (crossover binary representation)
s, d = kpoint(tonumber("10001", 2), tonumber("10110", 2), 5, 2, 3)
print(s) -- 23  which is (10111) in base 2
print(d) -- 16  which is (10000) in base 2


-- binary, (crossover base 10, but interpret as binary)
s, d = kpoint(1101, 1010, 4, 10, 3)
print(s) -- 1001
print(d) -- 1110