mirror of
https://github.com/onyx-and-iris/aoc2024.git
synced 2026-04-09 02:23:36 +00:00
add day-23 + benchmarks
This commit is contained in:
75
day-23/internal/set/set.go
Normal file
75
day-23/internal/set/set.go
Normal file
@@ -0,0 +1,75 @@
|
||||
package set
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// Set is a collection of unique elements
|
||||
type Set struct {
|
||||
elements map[string]struct{}
|
||||
}
|
||||
|
||||
// New creates a new set
|
||||
func New() *Set {
|
||||
return &Set{
|
||||
elements: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Set) String() string {
|
||||
l := s.List()
|
||||
slices.Sort(l)
|
||||
return fmt.Sprintf("%v", l)
|
||||
}
|
||||
|
||||
// Add inserts an element into the set
|
||||
func (s *Set) Add(value string) {
|
||||
s.elements[value] = struct{}{}
|
||||
}
|
||||
|
||||
// Remove deletes an element from the set
|
||||
func (s *Set) Remove(value string) {
|
||||
delete(s.elements, value)
|
||||
}
|
||||
|
||||
// Contains checks if an element is in the set
|
||||
func (s *Set) Contains(value string) bool {
|
||||
_, found := s.elements[value]
|
||||
return found
|
||||
}
|
||||
|
||||
// Size returns the number of elements in the set
|
||||
func (s *Set) Size() int {
|
||||
return len(s.elements)
|
||||
}
|
||||
|
||||
// List returns all elements in the set as a slice
|
||||
func (s *Set) List() []string {
|
||||
keys := make([]string, 0, len(s.elements))
|
||||
for key := range s.elements {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
func (s *Set) Union(other *Set) *Set {
|
||||
result := New()
|
||||
for key := range s.elements {
|
||||
result.Add(key)
|
||||
}
|
||||
for key := range other.elements {
|
||||
result.Add(key)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Set) Intersection(other *Set) *Set {
|
||||
result := New()
|
||||
for key := range s.elements {
|
||||
if other.Contains(key) {
|
||||
result.Add(key)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user