Skip to content

Instantly share code, notes, and snippets.

@prabod
Created December 3, 2016 19:47
Show Gist options
  • Save prabod/2a4c8486a4b1c9514b2bc35a2633933d to your computer and use it in GitHub Desktop.
Save prabod/2a4c8486a4b1c9514b2bc35a2633933d to your computer and use it in GitHub Desktop.
Crossover Function
/**
* 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