Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add Peek() method #3

Merged
merged 3 commits into from
Oct 30, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion pq.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import "container/heap"
type PQ interface {
// Push adds the ele
Push(Elem)
// Pop returns the highest priority Elem in PQ.
// Pop removes and returns the highest priority Elem in PQ.
Pop() Elem
// Peek returns the highest priority Elem in PQ (without removing it).
Peek() Elem
// Len returns the number of elements in the PQ.
Len() int
// Update `fixes` the PQ.
Expand Down Expand Up @@ -56,6 +58,13 @@ func (w *wrapper) Pop() Elem {
return heap.Pop(&w.heapinterface).(Elem)
}

func (w *wrapper) Peek() Elem {
if len(w.heapinterface.elems) == 0 {
return nil
}
return w.heapinterface.elems[0].(Elem)
}

func (w *wrapper) Update(index int) {
heap.Fix(&w.heapinterface, index)
}
Expand Down
13 changes: 12 additions & 1 deletion pq_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ func TestCorrectnessOfPop(t *testing.T) {
q.Push(&e)
}
var priorities []int
var peekPriorities []int
for q.Len() > 0 {
i := q.Pop().(*TestElem).Priority
t.Logf("popped %v", i)
priorities = append(priorities, i)
peekPriorities = append(peekPriorities, i)
}
if !sort.IntsAreSorted(priorities) {
if !sort.IntsAreSorted(peekPriorities) {
t.Fatal("the values were not returned in sorted order")
}
if !sort.IntsAreSorted(priorities) {
t.Fatal("the popped values were not returned in sorted order")
}
}

func TestUpdate(t *testing.T) {
Expand All @@ -73,12 +78,18 @@ func TestUpdate(t *testing.T) {
q.Push(middle)
q.Push(highest)
q.Push(lowest)
if q.Peek().(*TestElem).Key != highest.Key {
t.Fatal("head element doesn't have the highest priority")
}
if q.Pop().(*TestElem).Key != highest.Key {
t.Fatal("popped element doesn't have the highest priority")
}
q.Push(highest) // re-add the popped element
highest.Priority = 0 // update the PQ
q.Update(highest.Index()) // fix the PQ
if q.Peek().(*TestElem).Key != middle.Key {
t.Fatal("middle element should now have the highest priority")
}
if q.Pop().(*TestElem).Key != middle.Key {
t.Fatal("middle element should now have the highest priority")
}
Expand Down