adventofcode/helpers/queue.go

93 lines
1.9 KiB
Go
Raw Normal View History

2023-12-26 16:25:53 +00:00
package aoc
2023-12-28 19:48:29 +00:00
import "fmt"
2023-12-27 17:42:49 +00:00
type Queue[T any] struct {
2023-12-26 16:25:53 +00:00
items []T
}
2023-12-27 17:42:49 +00:00
func NewQueue[T any](items []T) *Queue[T] {
2023-12-26 16:25:53 +00:00
return &Queue[T]{
items: items,
}
}
func (q *Queue[T]) Len() int {
return len(q.items)
}
func (q *Queue[T]) Push(item T) {
q.items = append(q.items, item)
}
func (q *Queue[T]) Pop() T {
var x T
x, q.items = q.items[len(q.items)-1], q.items[:len(q.items)-1]
return x
}
func (q *Queue[T]) Unshift(item T) {
q.items = append([]T{item}, q.items...)
}
func (q *Queue[T]) Shift() T {
var x T
x, q.items = q.items[0], q.items[1:]
return x
}
func (q *Queue[T]) Append(items []T) {
q.items = append(q.items, items...)
}
func (q *Queue[T]) Copy() *Queue[T] {
ret := &Queue[T]{
items: make([]T, len(q.items)),
}
copy(ret.items, q.items)
return ret
}
func (q *Queue[T]) Cut(at, count int) []T {
ret := q.items[at : at+count]
q.items = append(q.items[:at], q.items[at+count:]...)
return ret
}
2023-12-27 17:42:49 +00:00
func (q *Queue[T]) DeleteAt(idx int) {
q.items = append(q.items[:idx], q.items[idx+1:]...)
2023-12-26 16:25:53 +00:00
}
2023-12-27 17:42:49 +00:00
// func (q *Queue[T]) Delete(item T) {
// for i := range q.items {
// if q.items[i] == item {
// q.items = append(q.items[:i], q.items[i+1:]...)
// return
// }
// }
// }
2023-12-26 16:25:53 +00:00
func (q *Queue[T]) Expand(at, by int) {
q.items = append(q.items[:at], append(make([]T, by), q.items[at:]...)...)
}
func (q *Queue[T]) Extend(by int) {
q.items = append(q.items, make([]T, by)...)
}
func (q *Queue[T]) FilterInPlace(keep func(item T) bool) {
n := 0
for _, x := range q.items {
if keep(x) {
q.items[n] = x
n++
}
}
q.items = q.items[:n]
}
func (q *Queue[T]) Insert(item T, location int) {
q.InsertVector([]T{item}, location)
}
func (q *Queue[T]) InsertVector(items []T, location int) {
q.items = append(q.items[:location], append(items, q.items[location:]...)...)
}
2023-12-28 19:48:29 +00:00
func (q Queue[T]) String() string {
res := "[ "
for i := range q.items {
res = fmt.Sprintf("%s %v", res, q.items[i])
}
return fmt.Sprintf("%s ]", res)
}