-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkey_value_pair_priority_queue.go
100 lines (82 loc) · 2.23 KB
/
key_value_pair_priority_queue.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
package datachan
import (
"container/heap"
)
// A StringKeyedMerge is something we manage in a priority queue.
type kvMerge struct {
value *keyValuePair
src <-chan *keyValuePair
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A StringKeyedPriorityQueue implements heap.Interface and holds Items.
type kvPairPriorityQueue []*kvMerge
func (pq kvPairPriorityQueue) Len() int { return len(pq) }
func (pq kvPairPriorityQueue) Less(i, j int) bool {
a := pq[i].value
b := pq[j].value
return a.less(b)
}
func (pq kvPairPriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *kvPairPriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*kvMerge)
item.index = n
*pq = append(*pq, item)
}
func (pq *kvPairPriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
func (pq *kvPairPriorityQueue) PopAndRefill() *keyValuePair {
node := heap.Pop(pq).(*kvMerge)
refillItem, ok := <-node.src
if ok {
heap.Push(pq, &kvMerge{
value: refillItem,
src: node.src,
})
}
return node.value
}
// A TopkeyValuePriorityQueueNode is something we manage in a priority queue.
type TopkeyValuePriorityQueueNode struct {
value *keyValuePair
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A TopKeyValuePriorityQueue implements heap.Interface and holds Items.
type TopKeyValuePriorityQueue []*TopkeyValuePriorityQueueNode
func (pq TopKeyValuePriorityQueue) Len() int { return len(pq) }
func (pq TopKeyValuePriorityQueue) Less(i, j int) bool {
a := pq[i].value
b := pq[j].value
return a.less(b)
}
func (pq TopKeyValuePriorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *TopKeyValuePriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*TopkeyValuePriorityQueueNode)
item.index = n
*pq = append(*pq, item)
}
func (pq *TopKeyValuePriorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}