-
Notifications
You must be signed in to change notification settings - Fork 1
/
dsu_test.go
135 lines (112 loc) · 2.24 KB
/
dsu_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
129
130
131
132
133
134
135
package dsu
import (
"math/rand"
"testing"
)
func assertEqual(t *testing.T, got, expected interface{}) {
t.Helper()
if got != expected {
t.Errorf("expected %v, got %v", expected, got)
}
}
func TestContains(t *testing.T) {
d := New()
d.Add(1)
d.Add("foo")
assertEqual(t, d.Contains(1), true)
assertEqual(t, d.Contains("foo"), true)
assertEqual(t, d.Contains(0), false)
}
func TestFind(t *testing.T) {
t.Run("Finding a non existing element", func(t *testing.T) {
d := New()
assertEqual(t, d.Find(1), nil)
})
t.Run("Finding an existing element", func(t *testing.T) {
d := New()
for i := 1; i <= 4; i++ {
d.Add(i)
}
d.Union(3, 2)
d.Union(4, 3)
assertEqual(t, d.Find(1), 1)
assertEqual(t, d.Find(2), 2)
assertEqual(t, d.Find(3), 2)
assertEqual(t, d.Find(4), 2)
})
}
func TestUnion(t *testing.T) {
t.Run("Union of non existing elements", func(t *testing.T) {
d := New()
d.Add(1)
assertEqual(t, d.Union(1, 2), false)
assertEqual(t, d.Union(2, 3), false)
})
t.Run("Union of existing elements", func(t *testing.T) {
d := New()
for i := 1; i <= 4; i++ {
d.Add(i)
}
d.Union(3, 2)
assertEqual(t, d.Union(2, 3), false)
assertEqual(t, d.Union(1, 3), true)
assertEqual(t, d.Union(1, 3), false)
assertEqual(t, d.Union(3, 4), true)
})
}
var result bool
func BenchmarkContains(b *testing.B) {
rand.Seed(42)
d := New()
for i := 0; i < 100000; i++ {
d.Add(rand.Intn(100000))
}
var r bool
b.ResetTimer()
for i := 0; i < b.N; i++ {
r = d.Contains(rand.Intn(100000))
}
result = r
}
func BenchmarkAdd(b *testing.B) {
rand.Seed(42)
d := New()
b.ResetTimer()
for i := 0; i < b.N; i++ {
d.Add(rand.Intn(100000))
}
}
func BenchmarkUnion(b *testing.B) {
rand.Seed(42)
d := New()
for i := 0; i < 100000; i++ {
d.Add(i)
}
var r bool
b.ResetTimer()
for i := 0; i < b.N; i++ {
x := rand.Intn(100000)
y := rand.Intn(100000)
r = d.Union(x, y)
}
result = r
}
var result2 interface{}
func BenchmarkFind(b *testing.B) {
rand.Seed(42)
d := New()
for i := 0; i < 100000; i++ {
d.Add(i)
}
for i := 0; i < 1000; i++ {
x := rand.Intn(100000)
y := rand.Intn(100000)
d.Union(x, y)
}
var r interface{}
b.ResetTimer()
for i := 0; i < b.N; i++ {
r = d.Find(rand.Intn(100000))
}
result2 = r
}