-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrossover_test.go
More file actions
87 lines (75 loc) · 2.15 KB
/
crossover_test.go
File metadata and controls
87 lines (75 loc) · 2.15 KB
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
86
87
package ga
import (
"fmt"
"math/rand"
"testing"
)
func TestDefaultCrossover(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
candidatePool := Population{
{Bitstring{"1", "0", "0", "0"}},
{Bitstring{"0", "0", "0", "1"}},
}
offspring, err := genA.Crossover(candidatePool[0], candidatePool[1], genA.RandomEngine)
if err != nil {
t.Error("Unexpected error:", err)
} else {
t.Log("Crossover threw no errors")
}
found := false
foundIndex := 0
expectedString := "{[1 0 0 1 ]}"
for i, val := range offspring {
if fmt.Sprint(val) == expectedString {
found = true
foundIndex = i
break
}
}
if !found {
t.Error("Crossover failed.", "Expected:", expectedString, "Got:", offspring[0])
} else {
t.Log("Crossover succeeded.", "Expected:", expectedString, "Got:", offspring[foundIndex])
}
}
func TestBadDefaultCrossover(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
candidatePool := Population{
{Bitstring{"1", "0", "0", "0"}},
{Bitstring{"0", "0", "0"}},
}
_, err := genA.Crossover(candidatePool[0], candidatePool[1], genA.RandomEngine)
if err == nil {
t.Error("Expected error but got:", err)
} else {
t.Log("Successfuly threw and caught err:", err)
}
}
func TestSetCrossoverFunc(t *testing.T) {
t.Parallel()
var genA = NewGeneticAlgorithm()
genA.SetSeed(3)
genA.SetOutputFunc(func(a ...interface{}) { t.Log(a...) })
genA.SetCrossoverFunc(func(gene, spouse Genome, random *rand.Rand) (Population, error) {
return Population{{Bitstring{"1", "2", "3", "4"}}}, nil
})
expectedString := "[{[1 2 3 4 ]}]"
crossoverGene, err := genA.Crossover(Genome{}, Genome{}, genA.RandomEngine)
if err != nil {
t.Error("Unexpected error:", err)
} else {
t.Log("Crossover threw no errors")
}
gotString := fmt.Sprint(crossoverGene)
if gotString != expectedString {
t.Error("Crossover function not set.", "Expected:", expectedString, "Got:", gotString)
} else {
t.Log("Crossover function set successfully.", "Expected:", expectedString, "Got:", gotString)
}
}