Genetic Algorithm
A naive try at creating a genetic algorithm in ES6
Installation
npm install genetalg
Usage
const populationSize = 200
const chromosomeLength = 40
const genesPool = [0, 1]
const population = new Population(populationSize, chromosomeLength, genesPool)
const nbGenerations = 10000
const fitnessFunction = chromosome => (
Math.random()
)
population.evolve(nbGenerations, fitnessFunction)
const bestChromosome = population.currentPopulation[0]
console.log(bestChromosome.dna)
console.log(bestChromosome.fitness)
Example
Trivial example to evolve a population that will have I AM A ROBOT AND I LIKE TO EAT BOLTS
written in their DNA
const alphabet = [ ' ', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]
const target = 'I AM A ROBOT AND I LIKE TO EAT BOLTS'
const fitnessFunction = chromosome => {
return chromosome.dna.split('')
.reduce((acc, current, i) => acc + (current === target[i] ? 1 : 0), 0) / target.length
}
const population = new Population(30, target.length, alphabet)
population.evolve(1200, fitnessFunction)
console.log(population.currentPopulation[0].dna)