-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkth_largest_element_test.go
107 lines (98 loc) · 2.82 KB
/
kth_largest_element_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
package kthlargestelement
import "testing"
func TestKthLargest(t *testing.T) {
tests := []struct {
name string
intArray []int
kthLargest int
expectedValue int
expectedErrorString string
}{
{
name: "7 is 5th largest value in sorted array",
intArray: []int{0, 1, 2, 3, 5, 7, 8, 9, 11, 13},
kthLargest: 5,
expectedValue: 7,
},
{
name: "9 is 4th largest value in unsorted array",
intArray: []int{7, 92, 23, 9, -1, 0, 11, 6},
kthLargest: 4,
expectedValue: 9,
},
{
name: "0-th largest value throws correct error",
intArray: []int{7, 92, 23, 9, -1, 0, 11, 6},
kthLargest: 0,
expectedErrorString: "Cannot find 0-th largest value in array",
},
{
name: "Empty array throws correct error",
intArray: []int{},
expectedErrorString: "Error finding kth largest of array: length of array is 0",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
if r != test.expectedErrorString {
t.Errorf("Expected error %s, received %s instead.", test.expectedErrorString, r)
}
}
}()
received := kthLargest(test.intArray, test.kthLargest)
if received != test.expectedValue {
t.Errorf("Expected %d, received %d instead.", test.expectedValue, received)
}
})
}
}
func TestRandomizedSelect(t *testing.T) {
tests := []struct {
name string
intArray []int
kthLargest int
expectedValue int
expectedErrorString string
}{
{
name: "7 is 5th largest value in sorted array",
intArray: []int{0, 1, 2, 3, 5, 7, 8, 9, 11, 13},
kthLargest: 5,
expectedValue: 7,
},
{
name: "9 is 4th largest value in unsorted array",
intArray: []int{7, 92, 23, 9, -1, 0, 11, 6},
kthLargest: 4,
expectedValue: 9,
},
{
name: "0-th largest value throws correct error",
intArray: []int{7, 92, 23, 9, -1, 0, 11, 6},
kthLargest: 0,
expectedErrorString: "Cannot find 0-th largest value in array",
},
{
name: "Empty array throws correct error",
intArray: []int{},
expectedErrorString: "Error finding kth largest of array: length of array is 0",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
defer func() {
if r := recover(); r != nil {
if r != test.expectedErrorString {
t.Errorf("Expected error %s, received %s instead.", test.expectedErrorString, r)
}
}
}()
received := randomizedSelect(test.intArray, test.kthLargest)
if received != test.expectedValue {
t.Errorf("Expected %d, received %d instead.", test.expectedValue, received)
}
})
}
}