-
Notifications
You must be signed in to change notification settings - Fork 5
/
deque_test.go
146 lines (128 loc) · 2.54 KB
/
deque_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
136
137
138
139
140
141
142
143
144
145
146
package memorycache
import (
"container/list"
"math/rand"
"testing"
"github.com/lxzan/memorycache/internal/utils"
"github.com/stretchr/testify/assert"
)
func validate(q *deque[int, int]) bool {
var sum = 0
for i := q.Get(q.head); i != nil; i = q.Get(i.next) {
sum++
next := q.Get(i.next)
if next == nil {
continue
}
if i.next != next.addr {
return false
}
if next.prev != i.addr {
return false
}
}
if q.Len() != sum {
return false
}
if head := q.Front(); head != nil {
if head.prev != 0 {
return false
}
}
if tail := q.Back(); tail != nil {
if tail.next != 0 {
return false
}
}
if q.Len() == 1 && q.Front().Value != q.Back().Value {
return false
}
return true
}
func TestQueue_Random(t *testing.T) {
var count = 10000
var q = newDeque[int, int](0)
var linkedlist = list.New()
for i := 0; i < count; i++ {
var flag = rand.Intn(7)
var val = rand.Int()
switch flag {
case 0, 1, 2, 3:
ele := q.PushBack()
ele.Value = val
linkedlist.PushBack(val)
case 4:
if q.Len() > 0 {
q.PopFront()
linkedlist.Remove(linkedlist.Front())
}
case 5:
var n = rand.Intn(10)
var index = 0
for iter := q.Front(); iter != nil; iter = q.Get(iter.next) {
index++
if index >= n {
q.MoveToBack(iter.addr)
break
}
}
index = 0
for iter := linkedlist.Front(); iter != nil; iter = iter.Next() {
index++
if index >= n {
linkedlist.MoveToBack(iter)
break
}
}
case 6:
var n = rand.Intn(10)
var index = 0
for iter := q.Front(); iter != nil; iter = q.Get(iter.next) {
index++
if index >= n {
q.Remove(iter.addr)
break
}
}
index = 0
for iter := linkedlist.Front(); iter != nil; iter = iter.Next() {
index++
if index >= n {
linkedlist.Remove(iter)
break
}
}
default:
}
}
assert.True(t, validate(q))
for i := linkedlist.Front(); i != nil; i = i.Next() {
var ele = q.PopFront()
assert.Equal(t, i.Value, ele.Value)
}
}
func TestDeque_Range(t *testing.T) {
var q = newDeque[string, int](8)
var push = func(values ...int) {
for _, v := range values {
q.PushBack().Value = v
}
}
push(1, 3, 5, 7, 9)
{
var arr []int
q.Range(func(ele *Element[string, int]) bool {
arr = append(arr, ele.Value)
return true
})
assert.True(t, utils.IsSameSlice(arr, []int{1, 3, 5, 7, 9}))
}
{
var arr []int
q.Range(func(ele *Element[string, int]) bool {
arr = append(arr, ele.Value)
return len(arr) < 3
})
assert.True(t, utils.IsSameSlice(arr, []int{1, 3, 5}))
}
}