-
Notifications
You must be signed in to change notification settings - Fork 0
/
linebreak_test.go
128 lines (99 loc) · 2.39 KB
/
linebreak_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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package linebreak_test
import (
"math"
"math/rand"
"reflect"
"testing"
"github.com/invisiblefunnel/linebreak"
)
func planarDist(a, b [2]float64) float64 {
dx := a[0] - b[0]
dy := a[1] - b[1]
return math.Sqrt(dx*dx + dy*dy)
}
func TestSolveBreaks(t *testing.T) {
var targetDist float64 = 11
points := [][2]float64{{0, 0}, {3, 8}, {4, 16}, {10, 23}, {11, 28}}
dists := make([]float64, len(points)-1)
for i := 0; i < len(points)-1; i++ {
dists[i] = planarDist(points[i], points[i+1])
}
var actual [][]int
linebreak.Solve(dists, targetDist, func(i, j int) {
actual = append(actual, []int{i, j})
})
expected := [][]int{{0, 1}, {1, 2}, {2, 4}}
if !reflect.DeepEqual(expected, actual) {
t.Fail()
}
}
func TestSolveBreaksNone(t *testing.T) {
points := [][2]float64{{0, 0}, {3, 8}, {4, 16}, {10, 23}, {11, 28}}
var totalDistance float64
dists := make([]float64, len(points)-1)
for i := 0; i < len(points)-1; i++ {
dist := planarDist(points[i], points[i+1])
dists[i] = dist
totalDistance += dist
}
var actual [][]int
linebreak.Solve(dists, totalDistance, func(i, j int) {
actual = append(actual, []int{i, j})
})
expected := [][]int{{0, len(points) - 1}}
if len(expected) != 1 {
t.Fail()
}
if expected[0][0] != 0 {
t.Fail()
}
if expected[0][1] != len(points)-1 {
t.Fail()
}
}
func TestSolveBreaksAll(t *testing.T) {
points := [][2]float64{{0, 0}, {3, 8}, {4, 16}, {10, 23}, {11, 28}}
minDistance := math.Inf(1)
dists := make([]float64, len(points)-1)
for i := 0; i < len(points)-1; i++ {
dist := planarDist(points[i], points[i+1])
dists[i] = dist
if dist < minDistance {
minDistance = dist
}
}
var actual [][]int
linebreak.Solve(dists, minDistance, func(i, j int) {
actual = append(actual, []int{i, j})
})
var expected [][]int
for i := 0; i < len(points)-1; i++ {
expected = append(expected, []int{i, i + 1})
}
if len(expected) != len(points)-1 {
t.Fail()
}
if !reflect.DeepEqual(expected, actual) {
t.Fail()
}
}
func BenchmarkSolve(b *testing.B) {
var (
N int = 1000
maxDist float64 = 100
targetDist float64 = maxDist * 2
)
dists := make([]float64, N)
for i := 0; i < N; i++ {
dists[i] = randFloat(0, 1000)
}
f := func(i, j int) {}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
linebreak.Solve(dists, targetDist, f)
}
}
func randFloat(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}