-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenetic_algorithm.js
46 lines (44 loc) · 1.38 KB
/
genetic_algorithm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class GeneticAlgorithm {
/**
* @param {Car[]} lastGeneration
*
* @returns {Car[]}
*/
static nextGeneration(lastGeneration) {
GeneticAlgorithm.calculateIndividualFitness(lastGeneration);
const totalFitness = lastGeneration.reduce((prev, curr) => prev + curr.fitness, 0);
const newGeneration = lastGeneration.map(() => {
const parent1 = GeneticAlgorithm.pickOne(lastGeneration, totalFitness);
const parent2 = GeneticAlgorithm.pickOne(lastGeneration, totalFitness);
const child = parent1.crossover(parent2);
child.mutate(0.1);
return child;
});
return newGeneration;
}
/**
* @param {Car[]} lastGeneration
* @param {number} totalFitness
*
* @returns {Car}
*/
static pickOne(lastGeneration, totalFitness) {
const r = Math.random() * totalFitness;
let currentCount = 0;
for (const parent of lastGeneration) {
currentCount += parent.fitness;
if (r <= currentCount) {
return parent;
}
}
throw new Error('PARENT NOT FOUND');
}
/**
* @param {Car[]} lastGeneration
*/
static calculateIndividualFitness(lastGeneration) {
for (const parent of lastGeneration) {
parent.fitness = parent.score * parent.score;
}
}
}