advent-of-code/search.go

36 lines
755 B
Go
Raw Normal View History

package aoc
import (
"sort"
)
2023-12-28 18:57:22 -07:00
type priorityQueue[T any, U []T] struct {
elems U
less func(a, b T) bool
}
2023-12-28 18:57:22 -07:00
func PriorityQueue[T any, U []T](less func(a, b T) bool) *priorityQueue[T, U] {
return &priorityQueue[T, U]{less: less}
}
2023-12-28 18:57:22 -07:00
func (pq *priorityQueue[T, U]) Enqueue(elem T) {
pq.elems = append(pq.elems, elem)
sort.Slice(pq.elems, func(i, j int) bool { return pq.less(pq.elems[j], pq.elems[i]) })
}
2023-12-28 18:57:22 -07:00
func (pq *priorityQueue[T, I]) IsEmpty() bool {
return len(pq.elems) == 0
}
2023-12-28 18:57:22 -07:00
func (pq *priorityQueue[T, I]) Dequeue() (T, bool) {
var elem T
if pq.IsEmpty() {
return elem, false
}
2023-12-28 18:57:22 -07:00
pq.elems, elem = pq.elems[:len(pq.elems)-1], pq.elems[len(pq.elems)-1]
return elem, true
}
2023-12-28 18:57:22 -07:00
type DS[T comparable] struct {
*priorityQueue[T, []T]
*set[T]
}