Skip to content

Instantly share code, notes, and snippets.

@deleteman
Created December 10, 2022 15:29
Show Gist options
  • Save deleteman/2e57a07c64d7216671e6d6dc3c47ed22 to your computer and use it in GitHub Desktop.
Save deleteman/2e57a07c64d7216671e6d6dc3c47ed22 to your computer and use it in GitHub Desktop.
// define a function to perform crossover between two individuals
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));
// return the offspring
return offspring;
};
// define a function to perform mutation on an individual
const mutation = (individual) => {
// iterate over the cities in the individual
for (let i = 0; i < NUM_CITIES; i++) {
// with probability MUTATION_RATE, swap this city with another city
if (Math.random() < MUTATION_RATE) {
let j = Math.floor(Math.random() * NUM_CITIES);
let temp = individual[i];
individual[i] = individual[j];
individual[j] = temp;
}
}
// return the mutated individual
return individual;
};
// define a function to evolve the population
const evolve = (population) => {
// select individuals for the next generation
let nextGeneration = selection(population);
// create the new generation by performing crossover and mutation
for (let i = 0; i < POPULATION_SIZE; i++) {
// with probability CROSSOVER_RATE, perform crossover
if (Math.random() < CROSSOVER_RATE) {
let individual1 = nextGeneration[i];
let individual2 = nextGeneration[Math.floor(Math.random() * POPULATION_SIZE)];
nextGeneration[i] = crossover(individual1, individual2);
}
// perform mutation on the individual
nextGeneration[i] = mutation(nextGeneration[i]);
}
// return the new generation
return nextGeneration;
};
// run the genetic algorithm for a specified number of iterations
for (let i = 0; i < MAX_ITERATIONS; i++) {
population = evolve(population);
}
// sort the population by fitness
population.sort((a, b) => calculateFitness(a) - calculateFitness(b));
// print the best individual
console.log(population[0]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment