-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpqueue.go
More file actions
101 lines (87 loc) · 1.82 KB
/
pqueue.go
File metadata and controls
101 lines (87 loc) · 1.82 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
99
100
101
package pqueue
import (
"container/heap"
"sync"
)
type Item struct {
Body string // data
Score int // priority
}
type PriorityQueue struct {
List []*Item
Cursor int // represents length of the PriorityQueue
}
func (pq *PriorityQueue) Len() int {
return (*pq).Cursor
}
func (pq *PriorityQueue) Less(i, j int) bool {
return pq.List[i].Score > pq.List[j].Score
}
func (pq *PriorityQueue) Swap(i, j int) {
pq.List[i], pq.List[j] = pq.List[j], pq.List[i]
}
func (pq *PriorityQueue) Push(x interface{}) {
current_length := (*pq).Cursor
item := x.(*Item)
(*pq).List[current_length] = item // last existing element is at index: Cursor-1
(*pq).Cursor = (*pq).Cursor + 1
}
func (pq *PriorityQueue) Pop() interface{} {
current_length := (*pq).Cursor
item := pq.List[current_length-1]
pq.List[current_length-1] = nil
(*pq).Cursor = (*pq).Cursor - 1
return item
}
type QMan struct {
Pq *PriorityQueue
mutex *sync.Mutex
}
func InitQ(length int) *QMan {
qm := &QMan{}
pq := &(PriorityQueue{
List: make([]*Item, length),
Cursor: 0,
})
heap.Init(pq)
qm.Pq = pq
qm.mutex = &sync.Mutex{}
return qm
}
func (fm *QMan) Qpush(c *Item) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
fm.mutex.Lock()
defer fm.mutex.Unlock()
heap.Push(fm.Pq, c)
return err
}
func (fm *QMan) Qpop() *Item {
fm.mutex.Lock()
defer fm.mutex.Unlock()
if fm.Pq.Len() <= 0 {
return nil
}
item := heap.Pop(fm.Pq).(*Item)
return item
}
func (fm *QMan) Qremove(i int) *Item {
fm.mutex.Lock()
defer fm.mutex.Unlock()
return heap.Remove(fm.Pq, i).(*Item)
}
func (fm *QMan) UpdatePriority(item *Item, newScore int) {
fm.mutex.Lock()
defer fm.mutex.Unlock()
item.Score = newScore
heap.Fix(fm.Pq, item.Score)
}
func MakeItem(body string, score int) *Item {
return &Item{
Body: body,
Score: score,
}
}