/
selector.go
39 lines (33 loc) · 925 Bytes
/
selector.go
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
package genetics
import (
"rand"
)
// Selects some subjects of the population
type Selector interface {
// Selects num individuals
Select(num int, population *Population) *Population
}
// Selects subject by stochastical criteria based on the
// fitness of the subject.
type StochasticSelector struct{}
func NewStochasticSelector() Selector {
return new(StochasticSelector)
}
func (sel *StochasticSelector) Select(num int, population *Population) (p *Population) {
p = NewPopulation(num)
for i := 0; i < num; i++ {
val := rand.Float64() * float64(population.FitnessSum)
p.Subjects[i] = getSubjectByProbability(val, population)
}
return
}
func getSubjectByProbability(val float64, population *Population) *Subject {
sum := Fitness(0)
for _, subject := range population.Subjects {
sum += subject.Fitness
if Fitness(val) < sum {
return subject
}
}
return population.Subjects[population.Size()-1]
}