-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxq
More file actions
42 lines (36 loc) · 851 Bytes
/
maxq
File metadata and controls
42 lines (36 loc) · 851 Bytes
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
# name: Max Queue
# key: maxq
# --
type ${1:Job} struct {
value ${2:string}
priority int
index int
}
// Create a ${3:PriorityQueue} of $1, sorted by maximum priority.
type $3 []*$1
func (pq $3) Len() int { return len(pq) }
func (pq $3) Less(i, j int) bool { return pq[i].priority > pq[j].priority }
func (pq $3) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
// heap.Push(pq, &$1{}) to add.
func (pq *$3) Push(x interface{}) {
n := len(*pq)
item := x.(*$1)
item.index = n
*pq = append(*pq, item)
}
// heap.Pop(pq) to retrieve the next $1.
// Don't forget to cast the returned item.
// e.g.., latest.(*$1)
func (pq *$3) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}