feat: stuff
This commit is contained in:
35
pkg/tools/heap/main.go
Normal file
35
pkg/tools/heap/main.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package heap
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"container/heap"
|
||||
)
|
||||
|
||||
type Heap[T any] struct {
|
||||
Data []T
|
||||
lessFunc func(a, b T) bool
|
||||
}
|
||||
|
||||
func More[T cmp.Ordered](x, y T) bool {
|
||||
return !cmp.Less(x, y) && x != y
|
||||
}
|
||||
|
||||
func NewBy[T any](lessFunc func(a, b T) bool, items ...T) *Heap[T] {
|
||||
h := &Heap[T]{items, lessFunc}
|
||||
heap.Init(h)
|
||||
return h
|
||||
}
|
||||
|
||||
func New[T cmp.Ordered](items ...T) *Heap[T] {
|
||||
return NewBy[T](func(a, b T) bool { return a < b }, items...)
|
||||
}
|
||||
|
||||
func (h Heap[T]) Len() int { return len(h.Data) }
|
||||
func (h Heap[T]) Less(i, j int) bool { return h.lessFunc(h.Data[i], h.Data[j]) }
|
||||
func (h Heap[T]) Swap(i, j int) { h.Data[i], h.Data[j] = h.Data[j], h.Data[i] }
|
||||
|
||||
func (h *Heap[T]) Push(x any) { h.Data = append(h.Data, x.(T)) }
|
||||
func (h *Heap[T]) Pop() any {
|
||||
defer func() { h.Data = h.Data[:len(h.Data)-1] }()
|
||||
return h.Data[len(h.Data)-1]
|
||||
}
|
||||
Reference in New Issue
Block a user