-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriorityqueue_test.go
More file actions
98 lines (82 loc) · 2.2 KB
/
Copy pathpriorityqueue_test.go
File metadata and controls
98 lines (82 loc) · 2.2 KB
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
package gds
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestPriorityQueue_Empty(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
assert.Equal(t, 0, pq.Len())
assert.True(t, pq.IsEmpty())
}
func TestPriorityQueue_MinHeap(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
pq.Push(5, 1, 3, 2, 4)
var got []int
for !pq.IsEmpty() {
v, ok := pq.Pop()
assert.True(t, ok)
got = append(got, v)
}
assert.Equal(t, []int{1, 2, 3, 4, 5}, got)
}
func TestPriorityQueue_MaxHeap(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a > b })
pq.Push(3, 1, 4, 1, 5, 9, 2, 6)
v, _ := pq.Pop()
assert.Equal(t, 9, v)
}
func TestPriorityQueue_Push_Single(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
pq.Push(42)
assert.Equal(t, 1, pq.Len())
}
func TestPriorityQueue_Pop_Empty(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
v, ok := pq.Pop()
assert.False(t, ok)
assert.Zero(t, v)
}
func TestPriorityQueue_Pop_LastElement(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
pq.Push(7)
v, ok := pq.Pop()
assert.True(t, ok)
assert.Equal(t, 7, v)
assert.True(t, pq.IsEmpty())
}
func TestPriorityQueue_Peek(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
pq.Push(3, 1, 2)
v, ok := pq.Peek()
assert.True(t, ok)
assert.Equal(t, 1, v)
assert.Equal(t, 3, pq.Len()) // not removed
}
func TestPriorityQueue_Peek_Empty(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
v, ok := pq.Peek()
assert.False(t, ok)
assert.Zero(t, v)
}
func TestPriorityQueue_CustomType(t *testing.T) {
type Task struct {
Name string
Priority int
}
pq := NewPriorityQueue(func(a, b Task) bool {
return a.Priority < b.Priority
})
pq.Push(Task{"low", 10}, Task{"high", 1}, Task{"mid", 5})
v, _ := pq.Pop()
assert.Equal(t, "high", v.Name)
}
func TestPriorityQueue_HeapProperty_AfterMultiplePops(t *testing.T) {
pq := NewPriorityQueue(func(a, b int) bool { return a < b })
pq.Push(10, 4, 7, 1, 8, 3)
prev, _ := pq.Pop()
for !pq.IsEmpty() {
v, _ := pq.Pop()
assert.LessOrEqual(t, prev, v)
prev = v
}
}