xxxxxxxxxx
90
class GeneticAlgorithm {
constructor(populationSize, chromosomeLength, mutationRate, crossoverRate, elitismCount) {
this.populationSize = populationSize;
this.chromosomeLength = chromosomeLength;
this.mutationRate = mutationRate;
this.crossoverRate = crossoverRate;
this.elitismCount = elitismCount;
this.population = [];
}
initialize() {
for (let i = 0; i < this.populationSize; i++) {
const chromosome = [];
for (let j = 0; j < this.chromosomeLength; j++) {
chromosome.push(Math.round(Math.random()));
}
this.population.push(chromosome);
}
}
calculateFitness(fitnessFunction) {
for (let i = 0; i < this.populationSize; i++) {
const chromosome = this.population[i];
const fitness = fitnessFunction(chromosome);
this.population[i] = { chromosome, fitness };
}
}
selection() {
const sortedPopulation = this.population.sort((a, b) => b.fitness - a.fitness);
return sortedPopulation.slice(0, this.elitismCount).map((individual) => individual.chromosome);
}
crossover(parent1, parent2) {
const crossoverPoint = Math.floor(Math.random() * this.chromosomeLength);
const offspring1 = parent1.slice(0, crossoverPoint).concat(parent2.slice(crossoverPoint));
const offspring2 = parent2.slice(0, crossoverPoint).concat(parent1.slice(crossoverPoint));
return [offspring1, offspring2];
}
mutation(chromosome) {
for (let i = 0; i < this.chromosomeLength; i++) {
if (Math.random() < this.mutationRate) {
chromosome[i] = chromosome[i] === 0 ? 1 : 0;
}
}
return chromosome;
}
evolve(fitnessFunction) {
this.calculateFitness(fitnessFunction);
const newPopulation = this.selection();
while (newPopulation.length < this.populationSize) {
const parent1 = this.population[Math.floor(Math.random() * this.elitismCount)].chromosome;
const parent2 = this.population[Math.floor(Math.random() * this.elitismCount)].chromosome;
let offspring = this.crossover(parent1, parent2);
offspring = offspring.map((child) => this.mutation(child));
newPopulation.push(offspring);
}
this.population = newPopulation;
}
}
// Define the fitness function
const fitnessFunction = (chromosome) => {
let fitness = 0;
for (let i = 0; i < chromosome.length; i++) {
fitness += chromosome[i];
}
return fitness;
};
// Create an instance of the GeneticAlgorithm class
const ga = new GeneticAlgorithm(100, 10, 0.01, 0.8, 5);
// Initialize the population
ga.initialize();
// Evolve the population for 100 generations
for (let i = 0; i < 100; i++) {
ga.evolve(fitnessFunction);
}
// Get the best chromosome
const bestChromosome = ga.population[0].chromosome;
console.log('Best chromosome:', bestChromosome);