Lua 3 point crossover help to start

327 views Asked by At

I want to implement a 3 point crossover for genetic programming but I don't know how to do it and where to start.

My input is:

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

For example a = {(12345,67890), (09876,54321)} (those are numbers, not strings)

Output: Something like this:

Example: a_1 = {(12895), (67340)} also numbers.

Thanks for reply and sorry for my bad English.

1

There are 1 answers

6
ryanpattison On BEST ANSWER

Here is my quick implementation of k-point crossover for integers using mostly integer arithmetic. Starting with this, you can extend it to crossover your chromosomes of many pairs of integers using a loop.

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