advent-of-code/set.go

69 lines
1.1 KiB
Go
Raw Permalink Normal View History

2023-12-28 18:57:22 -07:00
package aoc
import "golang.org/x/exp/maps"
2024-10-30 13:32:44 -06:00
type Set[T comparable] map[T]struct{}
2023-12-28 18:57:22 -07:00
2024-10-30 13:32:44 -06:00
func NewSet[T comparable](arr ...T) Set[T] {
m := make(Set[T], len(arr))
2023-12-28 18:57:22 -07:00
for _, a := range arr {
m[a] = struct{}{}
}
return m
}
2024-10-30 13:32:44 -06:00
func (m *Set[T]) Add(a T) {
2023-12-28 18:57:22 -07:00
(*m)[a] = struct{}{}
}
2024-10-30 13:32:44 -06:00
func (m *Set[T]) Items() []T {
2023-12-28 18:57:22 -07:00
return maps.Keys(*m)
}
2024-10-30 13:32:44 -06:00
func (m *Set[T]) Has(a T) bool {
2023-12-28 18:57:22 -07:00
var ok bool
_, ok = (*m)[a]
return ok
}
type defaultMap[K comparable, V any] struct {
m map[K]V
d V
}
func DefaultMap[K comparable, V any](d V) *defaultMap[K, V] {
return &defaultMap[K, V]{
make(map[K]V),
d,
}
}
func (m *defaultMap[K, V]) Set(k K, v V) {
m.m[k] = v
}
func (m *defaultMap[K, V]) Get(k K) (V, bool) {
if v, ok := m.m[k]; ok {
return v, true
}
return m.d, false
}
type pair[K, V any] struct {
K K
V V
}
func (m *defaultMap[K, V]) Items() []pair[K, V] {
var items = make([]pair[K, V], 0, len(m.m))
for k, v := range m.m {
items = append(items, pair[K, V]{k, v})
}
return items
}
2023-12-30 19:46:23 -07:00
func In[C comparable](n C, haystack ...C) bool {
for _, h := range haystack {
if n == h {
return true
}
}
return false
}