From 9936efa3e98d5090c534eb905c15bf0780a9ad1a Mon Sep 17 00:00:00 2001 From: Vincent Riva Date: Thu, 28 Mar 2019 04:34:25 +0100 Subject: [PATCH] Add variable mutationRate --- src/core/Population.ts | 9 +++++++-- src/example.ts | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/core/Population.ts b/src/core/Population.ts index 71b7c1f..984cbbd 100644 --- a/src/core/Population.ts +++ b/src/core/Population.ts @@ -7,6 +7,7 @@ export class Population { private blueprint: Blueprint; private chromosomes: Chromosome[]; private sumFitness: number; + private mutationRate: number; private fitnessCalculation: any; private render: any; @@ -16,6 +17,7 @@ export class Population { this.blueprint = blueprint; this.chromosomes = []; this.sumFitness = 0; + this.mutationRate = 0.01; this.initializeChromosomes(); } @@ -74,10 +76,13 @@ export class Population { this.chromosomes = [...this.chromosomes, ...newChromosomes]; } + setMutationRate(mutationRate: number) { + this.mutationRate = mutationRate; + } + mutateChromosones() { - const mutationRate = 0.01; this.chromosomes.map((chromosome: Chromosome) => { - if (Math.random() < mutationRate) { + if (Math.random() < this.mutationRate) { chromosome.mutate(); } }); diff --git a/src/example.ts b/src/example.ts index ad2c02f..84e3109 100644 --- a/src/example.ts +++ b/src/example.ts @@ -9,6 +9,7 @@ const blueprint = new Blueprint(); blueprint.add(26, answer.length); const population = new Population(200, blueprint); +population.setMutationRate(0.01); population.setFitnessCalculation((genes: Gene[]) => { let sum = 1; // Avoid to have 0 on fitness