-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevolver.go
76 lines (61 loc) · 1.33 KB
/
evolver.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"math/rand"
)
type Genome struct {
weights []float64
weightCount int
fitness float64
}
func NewGenome(weightCount int) Genome {
gen := Genome{make([]float64, weightCount), weightCount, -1000}
for i := range gen.weights {
gen.weights[i] = rand.Float64()
}
return gen
}
func (gen *Genome) Copy() Genome {
gen2 := Genome{
make([]float64, len(gen.weights)),
gen.weightCount,
gen.fitness,
}
copy(gen2.weights, gen.weights)
return gen2
}
type Population struct {
members []Genome
size int
}
func NewPopulation() Population {
return Population {
make([]Genome, 0),
0,
}
}
func (pop *Population) Add(g Genome){
pop.members = append(pop.members, g)
pop.size++
}
func (pop *Population) Set(g []Genome) {
pop.members = make([]Genome, len(g))
copy(pop.members, g)
pop.size = len(g)
}
func (pop *Population) Get(i int) *Genome {
return &pop.members[i]
}
func (pop *Population) GetRange(i, j int) []Genome {
return pop.members[i:j]
}
func (pop Population) Len() int {
return pop.size
}
func (pop Population) Less(i, j int) bool {
return pop.members[i].fitness < pop.members[j].fitness
}
func (pop Population) Swap(i, j int) {
g2 := pop.members[i].Copy()
pop.members[i] = pop.members[j].Copy()
pop.members[j] = g2
}