Skip to content

Commit 92683a4

Browse files
author
Rodrigo López Dato
committed
Return fittest gene of entire run
1 parent 5dce239 commit 92683a4

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

shared/src/main/scala/rolodato/genetics/Gene.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,11 @@ trait Gene {
4242
}
4343
}
4444
}
45+
46+
object Gene {
47+
val DummyGene = new Gene {
48+
def copy(newString: List[Int]): Gene = this
49+
def fitness: Double = Double.NegativeInfinity
50+
val string: List[Int] = List()
51+
}
52+
}

shared/src/main/scala/rolodato/genetics/Genetic.scala

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ trait Genetic {
3434
var population = initial.to[ListBuffer]
3535
var fitnesses = ListBuffer[Double]()
3636
val selectionSize = (population.length * selectionPercentage).toInt
37+
var best: Gene = Gene.DummyGene
3738
for (i <- 1 to iterations) {
3839
// Selection
3940
population = selection.selectPopulation(population, selectionSize).to[ListBuffer]
@@ -50,10 +51,16 @@ trait Genetic {
5051
population = population.updated(pos, mutation.mutate(population(pos)))
5152
}
5253
fitnesses += avgFitness(population)
54+
best = {
55+
val currentBest = population.maxBy(_.fitness)
56+
if (currentBest.fitness > best.fitness) currentBest
57+
else best
58+
}
5359
}
5460
new GeneticResult {
5561
val finalPopulation = population.sortBy(-_.fitness).toList
5662
val fitnessEvolution = fitnesses.toList
63+
val fittest = best
5764
}
5865
}
5966
}

shared/src/main/scala/rolodato/genetics/GeneticResult.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@ package rolodato.genetics
22

33
trait GeneticResult {
44
val finalPopulation: List[Gene]
5-
def fittest: Gene = finalPopulation.sortBy(-_.fitness).head
5+
val fittest: Gene
66
val fitnessEvolution: List[Double]
77
}

0 commit comments

Comments
 (0)