-
Notifications
You must be signed in to change notification settings - Fork 1
/
selector_base.go
85 lines (67 loc) · 1.93 KB
/
selector_base.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
77
78
79
80
81
82
83
84
85
package genetic_algorithm
import (
"fmt"
log "github.com/cihub/seelog"
)
// Base class for selectors.
type SelectorBase struct {
SelectorBaseVirtualMInterface
population Chromosomes
selectManyUnique bool
}
// SelectorBase's virtual methods
type SelectorBaseVirtualMInterface interface {
SelectInd() int
}
// Constructor for SelectorBase
func NewSelectorBase(virtual SelectorBaseVirtualMInterface) *SelectorBase {
selector := new(SelectorBase)
selector.SelectorBaseVirtualMInterface = virtual
selector.selectManyUnique = true
return selector
}
// Sets whether or not SelectMany will return only unique chromosomes
func (selector *SelectorBase) SelectManyAreUnique(value bool) *SelectorBase {
selector.selectManyUnique = value
return selector
}
func (selector *SelectorBase) Prepare(population Chromosomes) {
log.Tracef("Prepare Population=%d\n", len(population))
selector.population = population
}
func (selector *SelectorBase) Select() ChromosomeInterface {
return selector.population[selector.SelectorBaseVirtualMInterface.SelectInd()]
}
func (selector *SelectorBase) SelectMany(count int) Chromosomes {
log.Tracef("SelectMany c=%d\n", count)
if count < 0 {
panic("Count must be greater than 0")
}
if len(selector.population) < count && selector.selectManyUnique {
panic(fmt.Sprintf("Cant select %d unique chroms from %d chroms", count, len(selector.population)))
}
chroms := make(Chromosomes, count)
selected := make(map[int]bool, count)
for i := 0; i < count; i++ {
ind := selector.SelectorBaseVirtualMInterface.SelectInd()
if selector.selectManyUnique && selected[ind] {
j := 1
for {
if !selected[ind-j] && ind-j >= 0 {
ind = ind - j
break
}
if !selected[ind-j] && ind+j < len(selector.population) {
ind = ind + j
break
}
j++
}
}
selected[ind] = true
chrom := selector.population[ind]
log.Debugf("Parent[%d] - %v", i, chrom)
chroms[i] = chrom
}
return chroms
}