-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathselector_tournament_simple.go
46 lines (36 loc) · 1.01 KB
/
selector_tournament_simple.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
package genetic_algorithm
import (
"math/rand"
)
// Selects several random individuals from population and then selectd best.
type SimpleTournamentSelector struct {
*SelectorBase
contestants int
}
// Constructor for simple tournament selector.
// When contestants = 1 behaves like random selector
func NewSimpleTournamentSelector(contestants int) *SimpleTournamentSelector {
if contestants < 1 {
panic("Must be at least one contestant")
}
selector := new(SimpleTournamentSelector)
selector.SelectorBase = NewSelectorBase(selector)
selector.contestants = contestants
return selector
}
func NewRandomSelector() *SimpleTournamentSelector {
return NewSimpleTournamentSelector(1)
}
func (selector *SimpleTournamentSelector) SelectInd() int {
var bestCost float64
bestInd := -1
for i := 0; i < selector.contestants; i++ {
ind := rand.Intn(len(selector.population))
chrom := selector.population[ind]
if bestInd == -1 || chrom.Cost() < bestCost {
bestCost = chrom.Cost()
bestInd = ind
}
}
return bestInd
}