Skip to content

Instantly share code, notes, and snippets.

@deleteman
Created December 10, 2022 13:28
Show Gist options
  • Save deleteman/275491f737d89171b66108ad1268d047 to your computer and use it in GitHub Desktop.
Save deleteman/275491f737d89171b66108ad1268d047 to your computer and use it in GitHub Desktop.
const crossover = (individual1, individual2) => {
// choose a random crossover point
let point = Math.floor(Math.random() * NUM_CITIES);
// create the offspring by combining the two individuals
let offspring = individual1.slice(0, point).concat(individual2.slice(point));
// remove duplicate cities from the offspring
let uniqueCities = new Set(offspring);
offspring = [...uniqueCities];
// if the offspring is too short, add cities from the other individual
if (offspring.length < NUM_CITIES) {
for (let i = 0; i < NUM_CITIES; i++) {
if (!offspring.includes(individual1[i])) {
offspring.push(individual1[i]);
}
}
}
// return the offspring
return offspring;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment