-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority_queue.go
More file actions
105 lines (89 loc) · 1.82 KB
/
priority_queue.go
File metadata and controls
105 lines (89 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
102
103
104
105
package contour
import (
"sort"
)
type PriorityQueue struct {
items *items
sizeOption Option
}
type optionEnum int
const (
none optionEnum = iota
minPrioSize
maxPrioSize
)
type Option struct {
option optionEnum
value int
}
func NewPriorityQueue(options ...Option) *PriorityQueue {
pq := PriorityQueue{
items: &items{},
}
for _, o := range options {
switch o.option {
case none, minPrioSize, maxPrioSize:
pq.sizeOption = o
}
}
return &pq
}
func WithMinPrioSize(size int) Option {
return Option{
option: minPrioSize,
value: size,
}
}
func WithMaxPrioSize(size int) Option {
return Option{
option: maxPrioSize,
value: size,
}
}
func (p *PriorityQueue) Len() int {
return p.items.Len()
}
func (p *PriorityQueue) Insert(v interface{}, priority float64) {
*p.items = append(*p.items, &item{value: v, priority: priority})
sort.Sort(p.items)
switch p.sizeOption.option {
case minPrioSize:
if p.sizeOption.value < len(*p.items) {
*p.items = (*p.items)[:p.sizeOption.value]
}
case maxPrioSize:
diff := len(*p.items) - p.sizeOption.value
if diff > 0 {
*p.items = (*p.items)[diff:]
}
}
}
func (p *PriorityQueue) PopLowest() interface{} {
if len(*p.items) == 0 {
return nil
}
x := (*p.items)[0]
*p.items = (*p.items)[1:]
return x.value
}
func (p *PriorityQueue) PopHighest() interface{} {
l := len(*p.items) - 1
if l < 0 {
return nil
}
x := (*p.items)[l]
*p.items = (*p.items)[:l]
return x.value
}
func (p *PriorityQueue) Get(i int) (interface{}, float64) {
x := (*p.items)[i]
return x.value, x.priority
}
type items []*item
func (p items) Len() int { return len(p) }
func (p items) Less(i, j int) bool { return p[i].priority < p[j].priority }
func (p items) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type item struct {
value interface{}
priority float64
}