-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchromosome.go
59 lines (50 loc) · 1.21 KB
/
chromosome.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
package genetic_algorithm
import (
"bytes"
"fmt"
log "github.com/cihub/seelog"
)
type EmptyChromosomeConstructor func(genesLen int) ChromosomeInterface
type ChromosomeInterface interface {
Genes() GenesInterface
SetCost(float64)
Cost() float64
}
type Chromosomes []ChromosomeInterface
func (c Chromosomes) Len() int { return len(c) }
func (c Chromosomes) Less(i, j int) bool { return c[i].Cost() < c[j].Cost() }
func (c Chromosomes) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
func (c Chromosomes) SetCost(cost CostFunction) {
log.Tracef("Setting cost for %d chroms", len(c))
for i := 0; i < len(c); i++ {
var chrom = c[i]
chrom.SetCost(cost(chrom))
}
}
func (c Chromosomes) MeanCost() float64 {
if len(c) == 0 {
return 0
}
var sum float64
for _, chrom := range c {
sum += chrom.Cost()
}
return sum / float64(len(c))
}
func (c Chromosomes) String() string {
var buffer bytes.Buffer
for i := 0; i < len(c); i++ {
if i != 0 {
buffer.WriteString("\n")
}
buffer.WriteString(fmt.Sprintf("%v", c[i]))
}
return buffer.String()
}
type GenesInterface interface {
Len() int
Copy(genes GenesInterface, from1, from2, to2 int) int
Swap(int, int)
Get(int) interface{}
Set(int, interface{})
}