in src/genetic_algorithm.py [0:0]
def crossover_parents_to_create_children(parent_one, parent_two):
child1 = copy.deepcopy(parent_one)
child2 = copy.deepcopy(parent_two)
# sometimes we don't cross over, so use copies of the parents
if random.random() >= CROSSOVER_RATE:
return child1, child2
num_genes = len(parent_one.path)
start_cross_at = random.randint(0, num_genes - 2) # pick a point between 0 and the end - 2, so we can cross at least 1 stop
num_remaining = num_genes - start_cross_at
end_cross_at = random.randint(num_genes - num_remaining + 1, num_genes - 1)
for index in range(start_cross_at, end_cross_at + 1):
child1_stop = child1.path[index]
child2_stop = child2.path[index]
# if the same, skip it since there is no crossover needed at this gene
if child1_stop == child2_stop:
continue
# find within child1 and swap
first_found_at = child1.path.index(child1_stop)
second_found_at = child1.path.index(child2_stop)
child1.path[first_found_at], child1.path[second_found_at] = child1.path[second_found_at], child1.path[first_found_at]
# and the same for the second child
first_found_at = child2.path.index(child1_stop)
second_found_at = child2.path.index(child2_stop)
child2.path[first_found_at], child2.path[second_found_at] = child2.path[second_found_at], child2.path[first_found_at]
return child1, child2