Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type HeapItemItf ¶
type HeapItemItf interface { GetKey() interface{} GetPriority() int }
HeapItemItf items need to sort
func GetLargestNItems ¶
func GetLargestNItems(inputChan <-chan HeapItemItf, topN int) ([]HeapItemItf, error)
GetLargestNItems get N highest priority items
Example ¶
package main import ( "fmt" "github.com/Laisky/go-utils/structures" ) // Item item that need to sort type Item struct { p int k interface{} } // GetKey get key of item func (it *Item) GetKey() interface{} { return it.k } // GetPriority get priority of item func (it *Item) GetPriority() int { return it.p } func main() { var ( itemsWaitToSort = structures.HeapItemQ{ &Item{p: 1}, &Item{p: 3}, &Item{p: 55}, &Item{p: 2}, &Item{p: 4441}, &Item{p: 15555}, &Item{p: 122}, } itemChan = make(chan structures.HeapItemItf) ) go func() { for _, item := range itemsWaitToSort { itemChan <- item } close(itemChan) }() items, err := structures.GetLargestNItems(itemChan, 3) if err != nil { panic(err) } for _, item := range items { // 15555 // 4441 // 112 fmt.Println(item.GetPriority()) } }
Output:
func GetSmallestNItems ¶
func GetSmallestNItems(inputChan <-chan HeapItemItf, topN int) ([]HeapItemItf, error)
GetSmallestNItems get N smallest priority items
Example ¶
package main import ( "fmt" "github.com/Laisky/go-utils/structures" ) // Item item that need to sort type Item struct { p int k interface{} } // GetKey get key of item func (it *Item) GetKey() interface{} { return it.k } // GetPriority get priority of item func (it *Item) GetPriority() int { return it.p } func main() { var ( itemsWaitToSort = structures.HeapItemQ{ &Item{p: 1}, &Item{p: 3}, &Item{p: 55}, &Item{p: 2}, &Item{p: 4441}, &Item{p: 15555}, &Item{p: 122}, } itemChan = make(chan structures.HeapItemItf) ) go func() { for _, item := range itemsWaitToSort { itemChan <- item } close(itemChan) }() items, err := structures.GetSmallestNItems(itemChan, 3) if err != nil { panic(err) } for _, item := range items { // 1 // 2 // 3 fmt.Println(item.GetPriority()) } }
Output:
func GetTopKItems ¶
func GetTopKItems(inputChan <-chan HeapItemItf, topN int, isHighest bool) ([]HeapItemItf, error)
GetTopKItems calculate topN by heap use min-heap to calculates topN Highest items use max-heap to calculates topN Lowest items
type HeapItemQ ¶
type HeapItemQ []HeapItemItf
Click to show internal directories.
Click to hide internal directories.