Created
December 3, 2016 19:47
Crossover Function
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
/** | |
* Cross two Chromosomes and produce a child Chromosome | |
* */ | |
function crossover(chromosome1,chromosome2,rate,geneSize,chromoSize) { | |
var rand = Math.random(); // Random value for check crossover chance | |
if (rand < rate){ | |
var vString = []; | |
for (var i =0; i< chromoSize; i += geneSize){ | |
for(var j = 0; j < geneSize; j++){ | |
/** | |
* Evenly Choose a Parent for breeding*/ | |
var inheritedGene = (Math.random() < 0.5) ? chromosome1 : chromosome2; | |
var dna = inheritedGene.valueString[i+j]; | |
var randnum = Math.random(); // Random Number for Mutation chance | |
if (randnum < MUTATION_RATE){ | |
/** | |
* Mutate by some Amount*/ | |
dna += Math.random() * MUTATE_AMOUNT * 2 - MUTATE_AMOUNT; | |
} | |
if (dna < 0) | |
dna = 0; | |
if (dna > 1) | |
dna = 1; | |
vString.push(dna); | |
} | |
} | |
return new Chromosome(vString,geneSize,chromoSize); | |
} | |
/** | |
* If No chance for crossover. Return one of the parent Chromosome*/ | |
return (Math.random() < 0.5) ? chromosome1 : chromosome2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment