-
Notifications
You must be signed in to change notification settings - Fork 1
/
knapsack_fixtures_test.go
58 lines (47 loc) · 1.31 KB
/
knapsack_fixtures_test.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
package genetic_test
import (
"encoding/json"
"os"
)
var knapsackSolutionFixtures []*KnapsackSolution
func init() {
fixtures, err := readKnapsackFixtures()
if err != nil {
panic(err)
}
knapsackSolutionFixtures = fixtures
}
func readKnapsackFixtures() ([]*KnapsackSolution, error) {
type knapsackProblemJSON struct {
Items [][2]int `json:"items"`
WeightLimit int `json:"weight_limit"`
Solution []int `json:"solution"`
}
var problemsJSON []*knapsackProblemJSON
data, err := os.ReadFile("knapsack_problems.json")
if err != nil {
return nil, err
}
if err := json.Unmarshal(data, &problemsJSON); err != nil {
return nil, err
}
knapsackSolutionFixtures := make([]*KnapsackSolution, len(problemsJSON))
for i, problemJSON := range problemsJSON {
solution := &KnapsackSolution{
Problem: &KnapsackProblem{
WeightLimit: problemJSON.WeightLimit,
Items: make([]*KnapsackItem, len(problemJSON.Items)),
},
PackingList: make([]bool, len(problemJSON.Items)),
}
for j := 0; j < len(problemJSON.Items); j++ {
solution.Problem.Items[j] = &KnapsackItem{
Weight: problemJSON.Items[j][0],
Value: problemJSON.Items[j][1],
}
solution.PackingList[j] = problemJSON.Solution[j] == 1
}
knapsackSolutionFixtures[i] = solution
}
return knapsackSolutionFixtures, nil
}