-
Notifications
You must be signed in to change notification settings - Fork 7
/
simple_moving_average_test.go
72 lines (66 loc) · 1.51 KB
/
simple_moving_average_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
package statistics
import (
"fmt"
"testing"
)
func ExampleSimpleMovingAverage() {
sma := SimpleMovingAverage(3, 1, 2, 3, 4, 5, 6, 7, 8, 9)
fmt.Printf("The simple moving average over the last 3 datapoints of [1 2 3 4 5 6 7 8 9] is %v.\n", sma)
// Output:
// The simple moving average over the last 3 datapoints of [1 2 3 4 5 6 7 8 9] is [2 3 4 5 6 7 8].
}
func TestSimpleMovingAverage(t *testing.T) {
cases := []struct {
name string
input []int
k int
expected string
}{
{
name: "+1 repeating",
input: []int{1, 2, 3, 4, 5, 6, 7, 8, 9},
k: 3,
expected: "[2 3 4 5 6 7 8]",
},
{
name: "+1 +1 -2 repeating",
input: []int{1, 2, 3, 1, 2, 3, 1, 2, 3},
k: 3,
expected: "[2 2 2 2 2 2 2]",
},
{
name: "+4 -2 repeating",
input: []int{1, 5, 3, 7, 5, 9, 7, 11},
k: 3,
expected: "[3 5 5 7 7 9]",
},
{
name: "k larger than n",
input: []int{1, 2, 3, 4},
k: 10,
expected: "[2.5]",
},
{
name: "k < 1",
input: []int{1, 2, 3, 4},
k: -1,
expected: "[]",
},
}
for _, c := range cases {
c := c
t.Run(c.name, func(t *testing.T) {
t.Parallel()
actual := SimpleMovingAverage(c.k, c.input...)
if fmt.Sprintf("%v", actual) != c.expected {
t.Logf("expected %v, got %v", c.expected, actual)
t.FailNow()
}
})
}
}
func BenchmarkSimpleMovingAverage(b *testing.B) {
for i := 0; i < b.N; i++ {
SimpleMovingAverage(3, 3, 6, 2, 6, 2, 6, 7, 2, 5, 4, 2, 4, 6)
}
}