-
Notifications
You must be signed in to change notification settings - Fork 0
/
evolve.js
55 lines (47 loc) · 1.5 KB
/
evolve.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
47
48
49
50
51
52
53
54
55
/*
* The evolver will be used to combine all genetic operators
* and loop to evolve the wanted program
*
* mutate => {Function} used to mutate a selection of programs
* generate => {Function} used to create random programs and fill the new population until it has its initial size
* crossover => {Function} used to mate random programs of a selection
* population => {Array<Program>} initial random population
* stopWhen => {Function} used to decide when to stop the evolve loop
* onIteration => {Function} called on each evolve iteration
* select => {Function} used to select the best individuals for the next generation
*/
const random = array => () => {
return array[Math.floor(Math.random() * array.length)];
};
export const createEvolver = ({
mutate,
generate,
crossover,
population,
stopWhen,
onIteration,
select
}) => () => {
let counter = 0;
while (++counter) {
const [selection, bestFitness, bestProgram] = select(population);
const newPopulation = [
bestProgram,
...selection,
// ...mutate(population),
...mutate(selection),
...crossover(selection)
// ...crossover(population),
];
while (newPopulation.length < population.length) {
const result = generate();
// const result = random(population)();
newPopulation.push(result);
}
population = newPopulation;
onIteration(counter, bestFitness, bestProgram);
if (stopWhen(counter, bestFitness)) {
return [bestProgram, bestFitness];
}
}
};