Skip to content

Commit

Permalink
Update PQ.Pop() API to return the weight as well
Browse files Browse the repository at this point in the history
  • Loading branch information
minkezhang committed Sep 13, 2022
1 parent f61015f commit e75b7f3
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 14 deletions.
14 changes: 4 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,11 @@ func main() {
qmin.Push(42, 1)
qmax.Push(42, 1)

if p := qmin.Priority(); p != 1 {
panic(fmt.Sprintf("found an unexpected priority for the next element in the priority queue: %v", p))
if data, p := qmin.Pop(); p != 1 || data != 42 {
panic(fmt.Sprintf("found an unexpected value from pq.Pop(): %v, %v", p, data))
}
if p := qmax.Priority(); p != 10 {
panic(fmt.Sprintf("found an unexpected priority for the next element in the priority queue: %v", p))
}
if data := qmin.Pop(); data != 42 {
panic(fmt.Sprintf("did not find the correct value from the queue: %v", data))
}
if data := qmax.Pop(); data != 418 {
panic(fmt.Sprintf("did not find the correct value from the queue: %v", data))
if data, p := qmax.Pop(); p != 10 || data != 418 {
panic(fmt.Sprintf("found an unexpected value from pq.Pop(): %v, %v", p, data))
}
}
```
8 changes: 6 additions & 2 deletions pq/pq.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,5 +106,9 @@ func (pq *PQ[T]) Push(p T, priority float64) {
}
}

// Pop removes the node with the highest priority from the queue.
func (pq *PQ[T]) Pop() T { return heap.Pop(pq.heap).(*node[T]).p }
// Pop removes the node with the highest (or lowest) priority from the queue.
func (pq *PQ[T]) Pop() (T, float64) {
p := pq.Priority()
d := heap.Pop(pq.heap).(*node[T]).p
return d, p
}
6 changes: 4 additions & 2 deletions pq/pq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,8 @@ func TestPQ(t *testing.T) {

var got []X
for !pq.Empty() {
got = append(got, pq.Pop())
d, _ := pq.Pop()
got = append(got, d)
}

if diff := cmp.Diff(
Expand All @@ -194,7 +195,8 @@ func TestPQ(t *testing.T) {

var got []X
for !pq.Empty() {
got = append(got, pq.Pop())
d, _ := pq.Pop()
got = append(got, d)
}

if diff := cmp.Diff(
Expand Down

0 comments on commit e75b7f3

Please sign in to comment.