Created
December 10, 2022 12:54
-
-
Save deleteman/7a2333f612ed35cf5d921bc7c624c7b5 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
// define a function to select individuals for the next generation | |
const selection = (population) => { | |
// calculate the fitness of each individual | |
let fitnesses = population.map(calculateFitness); | |
// normalize the fitness values | |
let totalFitness = fitnesses.reduce((a, b) => a + b, 0); | |
let probabilities = fitnesses.map((fitness) => fitness / totalFitness); | |
// select individuals for the next generation | |
let nextGeneration = []; | |
for (let i = 0; i < POPULATION_SIZE; i++) { | |
// choose two individuals based on their probabilities | |
let individual1 = Math.random(); | |
let individual2 = Math.random(); | |
let prob1 = 0; | |
let prob2 = 0; | |
let index1 = 0; | |
let index2 = 0; | |
for (let j = 0; j < POPULATION_SIZE; j++) { //find the first suitable individual based on probability | |
prob1 += probabilities[j]; | |
if (individual1 < prob1) { | |
index1 = j; | |
break; | |
} | |
} | |
//find the second one as long as it's not the one we picked before | |
for (let j = 0; j < POPULATION_SIZE; j++) { | |
if (j === index1) continue; | |
prob2 += probabilities[j]; | |
if (individual2 < prob2) { | |
index2 = j; | |
break; | |
} | |
} | |
// add the fittest individual to the next generation | |
nextGeneration.push(calculateFitness(population[index1]) < calculateFitness(population[index2]) ? population[index1] : population[index2]); | |
} | |
return nextGeneration | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment