Skip to content

Commit

Permalink
Fix bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
ralgond committed Sep 14, 2023
1 parent ffd905f commit 23cea3f
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 8 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
module github.com/ralgond/topk

go 1.21.1
29 changes: 21 additions & 8 deletions topk.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package topk

import (
"container/heap"
"container/heap";
"fmt";
)

// An Item is something we manage in a priority queue.
Expand Down Expand Up @@ -32,7 +33,7 @@ func (pq PriorityQueue) Len() int { return pq.n }
func (pq PriorityQueue) Less(i, j int) bool {
// fmt.Printf("Less, i:%d, j:%d, item_array.len:%d, pi:%p, pj:%p", i, j, pq.n, pq.item_array[i], pq.item_array[j])
// We want Pop to give us the highest, not lowest, priority so we use greater than here.
return pq.item_array[i].priority > pq.item_array[j].priority
return pq.item_array[i].priority < pq.item_array[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
Expand Down Expand Up @@ -64,8 +65,8 @@ func (pq *PriorityQueue) Pop() any {
}

func (pq *PriorityQueue) Top() *Item {
n := pq.n
item := pq.item_array[n-1]
//n := pq.n
item := pq.item_array[0]
return item
}

Expand All @@ -74,9 +75,8 @@ func (pq *PriorityQueue) TryPush(x any) {
if pq.n == pq.capacity {
top := pq.Top()
if item.priority > top.priority {
pq.Pop()
pq.Push(item)
heap.Fix(pq, pq.n-1)
heap.Pop(pq)
heap.Push(pq, item)
}
} else {
pq.Push(item)
Expand All @@ -98,9 +98,11 @@ type TOPK struct {
}

func NewTOPK(k int) *TOPK {
return &TOPK {
ret := &TOPK {
pq : NewPriorityQueueForTopK(k),
}
ret.Init()
return ret
}

func (topk *TOPK) Init() {
Expand All @@ -110,3 +112,14 @@ func (topk *TOPK) Init() {
func (topk *TOPK) Add(item *Item) {
topk.pq.TryPush(item)
}

func (topk *TOPK) Add2(value int, priority int) {
topk.pq.TryPush(&Item{value:value, priority:priority})
}

func (topk *TOPK) Dump() {
for i:=0; i < topk.pq.n; i++ {
item := topk.pq.item_array[i]
fmt.Printf("%d: %d\n", item.value, item.priority)
}
}
29 changes: 29 additions & 0 deletions topk_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package topk

import "testing"

func Test1(t *testing.T) {
topk := NewTOPK(3)

topk.Add2(1,1)
topk.Add2(2,2)
topk.Add2(3,3)
topk.Add2(4,4)
topk.Add2(5,5)
topk.Add2(6,6)

topk.Dump()
}

func Test2(t *testing.T) {
topk := NewTOPK(3)

topk.Add2(3,3)
topk.Add2(4,4)
topk.Add2(6,6)
topk.Add2(1,1)
topk.Add2(2,2)
topk.Add2(5,5)

topk.Dump()
}

0 comments on commit 23cea3f

Please sign in to comment.