| 1 |
// Package priority provides priority queue. |
| 2 |
package priority |
| 3 |
|
| 4 |
import ( |
| 5 |
"container/heap" |
| 6 |
) |
| 7 |
|
| 8 |
// An Item is something we manage in a priority queue. |
| 9 |
type Item struct { |
| 10 |
Value string // The value of the item; arbitrary. |
| 11 |
Priority int64 // The priority of the item in the queue. |
| 12 |
// The index is needed by update and is maintained by the heap.Interface methods. |
| 13 |
index int // The index of the item in the heap. |
| 14 |
} |
| 15 |
|
| 16 |
// A Queue implements heap.Interface and holds Items. |
| 17 |
type Queue []*Item |
| 18 |
|
| 19 |
// Len ... |
| 20 |
func (pq Queue) Len() int { |
| 21 |
return len(pq) |
| 22 |
} |
| 23 |
|
| 24 |
// Less ... |
| 25 |
func (pq Queue) Less(i, j int) bool { |
| 26 |
return pq[i].Priority < pq[j].Priority |
| 27 |
} |
| 28 |
|
| 29 |
// Swap ... |
| 30 |
func (pq Queue) Swap(i, j int) { |
| 31 |
pq[i], pq[j] = pq[j], pq[i] |
| 32 |
pq[i].index = i |
| 33 |
pq[j].index = j |
| 34 |
} |
| 35 |
|
| 36 |
// Push value into queue. |
| 37 |
func (pq *Queue) Push(x interface{}) { |
| 38 |
n := len(*pq) |
| 39 |
item := x.(*Item) |
| 40 |
item.index = n |
| 41 |
*pq = append(*pq, item) |
| 42 |
} |
| 43 |
|
| 44 |
// Pop value from queue. |
| 45 |
func (pq *Queue) Pop() interface{} { |
| 46 |
old := *pq |
| 47 |
n := len(old) |
| 48 |
item := old[n-1] |
| 49 |
item.index = -1 // for safety |
| 50 |
*pq = old[0 : n-1] |
| 51 |
return item |
| 52 |
} |
| 53 |
|
| 54 |
// MakeQueue allows to create priority queue. |
| 55 |
func MakeQueue() Queue { |
| 56 |
pq := make(Queue, 0) |
| 57 |
heap.Init(&pq) |
| 58 |
return pq |
| 59 |
} |