From c3358a0bd6a6f284ca5bea5f88e08e6789109b57 Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Wed, 4 May 2022 23:45:53 +0800 Subject: [PATCH] set --- sets/hash_set.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++ sets/set.go | 4 +++ sets/sorted_set.go | 8 ++++++ 3 files changed, 84 insertions(+) create mode 100644 sets/hash_set.go create mode 100644 sets/set.go create mode 100644 sets/sorted_set.go diff --git a/sets/hash_set.go b/sets/hash_set.go new file mode 100644 index 0000000..66e6452 --- /dev/null +++ b/sets/hash_set.go @@ -0,0 +1,72 @@ +package sets + +type hash_set[T comparable] map[T]struct{} + +func NewHashSet[T comparable](values ...T) hash_set[T] { + set := make(hash_set[T], len(values)) + set.Add(values...) + return set +} + +func (s hash_set[T]) Add(values ...T) { + for _, v := range values { + s[v] = struct{}{} + } +} + +func (s hash_set[T]) Remove(v T) { + delete(s, v) +} + +func (s hash_set[T]) Contain(value T) bool { + _, ok := s[value] + return ok +} + +func (s hash_set[T]) Clone() hash_set[T] { + set := NewHashSet[T]() + set.Add(s.Values()...) + return set +} + +func (s hash_set[T]) Iterate(fn func(value T)) { + for v := range s { + fn(v) + } +} + +// Union creates a new set contain all element of set s and other +func (s hash_set[T]) Union(other hash_set[T]) hash_set[T] { + set := s.Clone() + set.Add(other.Values()...) + return set +} + +// Intersection creates a new set whose element both be contained in set s and other +func (s hash_set[T]) Intersection(other hash_set[T]) hash_set[T] { + set := NewHashSet[T]() + s.Iterate(func(value T) { + if other.Contain(value) { + set.Add(value) + } + }) + + return set +} + +func (s hash_set[T]) Values() []T { + values := make([]T, 0, s.Size()) + s.Iterate(func(value T) { + values = append(values, value) + }) + + return values +} + +func (s hash_set[T]) IsEmpty() bool { + return len(s) == 0 +} + +func (s hash_set[T]) Size() int { + return len(s) +} diff --git a/sets/set.go b/sets/set.go new file mode 100644 index 0000000..fba7e98 --- /dev/null +++ b/sets/set.go @@ -0,0 +1,4 @@ +package sets + +type Set[T comparable] interface { +} diff --git a/sets/sorted_set.go b/sets/sorted_set.go new file mode 100644 index 0000000..7c9d6e4 --- /dev/null +++ b/sets/sorted_set.go @@ -0,0 +1,8 @@ +package sets + +type sorted_set[T comparable] struct { + sorted []T + set Set[T] +} + +