Created
December 10, 2022 13:28
-
-
Save deleteman/275491f737d89171b66108ad1268d047 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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