-
Notifications
You must be signed in to change notification settings - Fork 97
/
median_test.go
69 lines (61 loc) · 2.07 KB
/
median_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
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package honorsclass
import (
"math/big"
"math/rand"
"reflect"
"sort"
"testing"
"github.com/mrekucci/epi/lists"
)
func TestMedianOfSorted(t *testing.T) {
for _, test := range []struct {
l []interface{}
i int
want *big.Rat
err error
}{
// Test for errors.
{[]interface{}{"x"}, 0, nil, ErrType},
{[]interface{}{0, 2, 1, 3}, 0, nil, ErrSort},
{[]interface{}{0, 1, 2}, -1, nil, ErrNode},
// Test lists with cycle.
{[]interface{}{1}, 0, big.NewRat(1, 1), nil},
{[]interface{}{0, 1}, 0, big.NewRat(1, 2), nil},
{[]interface{}{0, 1, 2}, 0, big.NewRat(1, 1), nil},
{[]interface{}{0, 1, 2, 3}, 0, big.NewRat(1+2, 2), nil},
{[]interface{}{10, 20, 30}, 1, big.NewRat(20, 1), nil},
{[]interface{}{10, 20, 30, 40}, 2, big.NewRat(20+30, 2), nil},
{[]interface{}{10, 20, 30, 40, 50}, 4, big.NewRat(30, 1), nil},
// Test lists without cycle.
{[]interface{}{}, -1, nil, nil},
{[]interface{}{0, 1, 2, 3, 4, 5}, -1, big.NewRat(2+3, 2), nil},
{[]interface{}{10, 20, 30, 40, 50}, -1, big.NewRat(30, 1), nil},
} {
l, n := lists.CreateCycle(test.l, test.i)
if test.err == ErrNode { // Setup an unknown node for an ErrNode test.
n = &lists.Node{}
}
if got, err := MedianOfSorted(l, n); !reflect.DeepEqual(got, test.want) || err != test.err {
t.Errorf("MedianOfSorted(%v, %v) = %v, %v; want %v, %v", test.l, n, got, err, test.want, test.err)
}
}
}
func benchMedianOfSorted(b *testing.B, size int) {
ints := rand.New(rand.NewSource(int64(size))).Perm(size)
sort.Ints(ints)
data := make([]interface{}, size)
for i, n := range ints {
data[i] = n
}
l, n := lists.CreateCycle(data, 0)
b.ResetTimer()
for i := 0; i < b.N; i++ {
MedianOfSorted(l, n)
}
}
func BenchmarkMedianOfSorted1e1(b *testing.B) { benchMedianOfSorted(b, 1e1) }
func BenchmarkMedianOfSorted1e2(b *testing.B) { benchMedianOfSorted(b, 1e2) }
func BenchmarkMedianOfSorted1e3(b *testing.B) { benchMedianOfSorted(b, 1e3) }