Files
math/averager_heap.go
T

63 lines
1.9 KiB
Go
Raw Normal View History

2025-08-18 13:18:19 -05:00
// Copyright (C) 2019-2024, Lux Industries Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package math
import (
"github.com/luxfi/math/heap"
2025-08-18 13:18:19 -05:00
)
2026-02-04 15:43:42 -08:00
// AveragerHeap maintains a heap of the averagers keyed by a comparable type.
// K is the key type (e.g., ids.NodeID).
type AveragerHeap[K comparable] interface {
// Add the average to the heap. If key is already in the heap, the
2025-08-18 13:18:19 -05:00
// average will be replaced and the old average will be returned. If there
// was not an old average, false will be returned.
2026-02-04 15:43:42 -08:00
Add(key K, averager Averager) (Averager, bool)
2025-08-18 13:18:19 -05:00
// Remove attempts to remove the average that was added with the provided
2026-02-04 15:43:42 -08:00
// key, if none is contained in the heap, [false] will be returned.
Remove(key K) (Averager, bool)
2025-08-18 13:18:19 -05:00
// Pop attempts to remove the node with either the largest or smallest
// average, depending on if this is a max heap or a min heap, respectively.
2026-02-04 15:43:42 -08:00
Pop() (K, Averager, bool)
2025-08-18 13:18:19 -05:00
// Peek attempts to return the node with either the largest or smallest
// average, depending on if this is a max heap or a min heap, respectively.
2026-02-04 15:43:42 -08:00
Peek() (K, Averager, bool)
2025-08-18 13:18:19 -05:00
// Len returns the number of nodes that are currently in the heap.
Len() int
}
2026-02-04 15:43:42 -08:00
type averagerHeap[K comparable] struct {
heap heap.Map[K, Averager]
2025-08-18 13:18:19 -05:00
}
// NewMaxAveragerHeap returns a new empty max heap. The returned heap is not
// thread safe.
2026-02-04 15:43:42 -08:00
func NewMaxAveragerHeap[K comparable]() AveragerHeap[K] {
return averagerHeap[K]{
heap: heap.NewMap[K, Averager](func(a, b Averager) bool {
2025-08-18 13:18:19 -05:00
return a.Read() > b.Read()
}),
}
}
2026-02-04 15:43:42 -08:00
func (h averagerHeap[K]) Add(key K, averager Averager) (Averager, bool) {
return h.heap.Push(key, averager)
2025-08-18 13:18:19 -05:00
}
2026-02-04 15:43:42 -08:00
func (h averagerHeap[K]) Remove(key K) (Averager, bool) {
return h.heap.Remove(key)
2025-08-18 13:18:19 -05:00
}
2026-02-04 15:43:42 -08:00
func (h averagerHeap[K]) Pop() (K, Averager, bool) {
2025-08-18 13:18:19 -05:00
return h.heap.Pop()
}
2026-02-04 15:43:42 -08:00
func (h averagerHeap[K]) Peek() (K, Averager, bool) {
2025-08-18 13:18:19 -05:00
return h.heap.Peek()
}
2026-02-04 15:43:42 -08:00
func (h averagerHeap[K]) Len() int {
2025-08-18 13:18:19 -05:00
return h.heap.Len()
}