-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection.go
More file actions
48 lines (40 loc) · 1.25 KB
/
selection.go
File metadata and controls
48 lines (40 loc) · 1.25 KB
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
package ga
import (
"math/rand"
)
type SelectFunction func(FitnessFunction, Population, *rand.Rand) Population
var TournamentSelection SelectFunction = func(Fitness FitnessFunction, candidatePool Population, random *rand.Rand) Population {
offspring := make(Population, 0)
for i := 0; i < len(candidatePool); i++ {
parent1 := candidatePool[random.Int()%len(candidatePool)]
parent2 := candidatePool[random.Int()%len(candidatePool)]
if Fitness(parent1) > Fitness(parent2) {
offspring = append(offspring, parent1)
} else {
offspring = append(offspring, parent2)
}
}
return offspring
}
var RouletteSelection SelectFunction = func(Fitness FitnessFunction, candidatePool Population, random *rand.Rand) Population {
offspring := make(Population, 0)
for range candidatePool {
weightSum := 0
for _, val := range candidatePool {
weightSum += Fitness(val)
}
choice := random.Float32() * float32(weightSum)
for _, val := range candidatePool {
choice -= float32(Fitness(val))
if choice <= 0 {
offspring = append(offspring, val.Copy())
break
}
}
}
return offspring
}
// SetSelectionFunc changes the selection function to the function specified
func (genA *GeneticAlgorithm) SetSelectionFunc(f SelectFunction) {
genA.Selection = f
}