Good night, I'm breaking my head to find the error, is the following I'm crossing this list of binary numbers, the first crossing is working but the second is getting the end of the first, to exemplify this is my my list of entry:
SELECTED POPULATION
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '1', '1', '1']
['1', '1', '0', '0', '0', '1']
['0', '0', '0', '0', '1', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['0', '0', '1', '0', '0', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
These are the ones that will cross in pairs (father and mother):
CROSSOVER
INDICES: [0, 1, 2, 3, 4, 6, 7, 8]
Corte em: 6
Pai: ['1', '0', '1', '0', '1', '0']
Mae: ['1', '0', '1', '1', '1', '1']
Corte em: 2
Pai: ['1', '1', '0', '0', '0', '1']
Mae: ['0', '0', '0', '0', '1', '1']
Corte em: 1
Pai: ['1', '0', '1', '0', '1', '0']
Mae: ['1', '0', '1', '0', '1', '0']
Corte em: 2
Pai: ['0', '0', '1', '0', '0', '1']
Mae: ['1', '0', '1', '0', '1', '0']
And this is my output that is wrong:
CROSSOVER POPULATION
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '1', '1', '1']
['1', '1', '0', '0', '1', '1']
['0', '0', '0', '0', '1', '1']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['0', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
['1', '0', '1', '0', '1', '0']
CODE
def crossover(probCrossover):
indices = []
randoms = []
print('\nCROSSOVER')
print('-----'*6)
for i in range(len(populacao)):
randoms.append(random())
for i , r in enumerate(randoms):
if r <= probCrossover:
indices.append(i)
if len(indices)%2!=0:
indices.pop()
print('\nINDICES: {}'.format(indices))
for ind in range(0, len(indices), 2):
pontoCorte = randint(1, precind)
print('Corte em: {}'.format(pontoCorte))
print('Pai: {}\nMae: {}'.format(populacao[indices[ind]], populacao[indices[ind+1]]))
populacao.__setitem__(indices[ind], populacao[indices[ind]][0:pontoCorte]+populacao[indices[ind+1]][pontoCorte:])
populacao.__setitem__(indices[ind+1], populacao[indices[ind+1]][0:pontoCorte]+populacao[indices[ind]][pontoCorte:])