Created
January 22, 2016 15:53
-
-
Save lovasoa/04726aea9f14f9d4a37e to your computer and use it in GitHub Desktop.
Fast genetic library in javascript
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
class Genetic { | |
constructor(conf) { | |
this.setConfiguration(conf); | |
this.population = new Int32Array(this.conf.genomeLength * this.conf.populationSize); | |
for (let i=0; i<this.conf.populationSize; i++) this.seedGenome(this.getGenome(i)); | |
} | |
setConfiguration(conf) { | |
this.conf = Object.assign({ | |
populationSize: 100, | |
genomeLength: 10, | |
geneticDrift: 100 | |
}, conf); | |
} | |
getGenome(individualIndex) { | |
const len = this.conf.genomeLength, i = len * individualIndex; | |
return this.population.subarray(i, i + len); | |
} | |
/**Writes a random genome**/ | |
seedGenome(genome) { | |
for(let i=0; i<genome.length; i++) genome[i] = Genetic.randomInt(0, this.conf.drift); | |
} | |
/** Write a mutated version of parent to child**/ | |
mutate(parent, child) { | |
const drift = this.conf.geneticDrift; | |
for(let i=0; i<parent.length; i++){ | |
child[i] = parent[i] + Genetic.randomInt(0, drift) - drift/2; | |
} | |
} | |
/** Creates a new genome from the crossover of father and mother and write it to child**/ | |
crossover(father, mother, child) { | |
const start = Genetic.randomInt(0, father.length), | |
end = Genetic.randomInt(0, father.length); | |
for(let i=0; i<mother.length; i++) | |
child[i] = (start < i && i < end) ? father[i] : mother[i]; | |
} | |
/** Returns a random integer in range [from, to[ **/ | |
static randomInt(from, to) { | |
return to + Math.floor(Math.random()*(from-to)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment