NOTE
2.5 set
An unordered set without duplicate elements.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What It Is
- An unordered collection without duplicate elements
1.1. Data Structure
- hashmap
1.2. API
type ISet interface {
// Print set
String() string
// Number of elements in set
Length() int
// Whether set is empty
IsEmpty() bool
// Add an element to set
Add(data model.Comparable)
// Remove an element from set
Remove(data model.Comparable)
// Whether set contains an element
Contains(data model.Comparable) bool
}
1.3. Implementation
type Set struct {
m _map.IMap
}
func NewBstSet() *Set {
return &Set{m: _map.NewBstMap()}
}
func (b *Set) String() string {
return b.m.String()
}
func (b *Set) Length() int {
return b.m.Length()
}
func (b *Set) IsEmpty() bool {
return b.m.IsEmpty()
}
func (b *Set) Add(data model.Comparable) {
b.m.Add(data, nil)
}
func (b *Set) Remove(data model.Comparable) {
b.m.Remove(data)
}
func (b *Set) Contains(data model.Comparable) bool {
return b.m.Contains(data)
}
1.3.1. Test
func TestBstSet(t *testing.T) {
set := NewBstSet()
fmt.Println("initial set:",set)
e1 := model.NewElement(1)
e2 := model.NewElement(2)
e3 := model.NewElement(3)
e4 := model.NewElement(4)
e5 := model.NewElement(5)
set.Add(e1)
set.Add(e2)
set.Add(e3)
set.Add(e4)
set.Add(e5)
set.Add(e5)
fmt.Println("set after adding elements:",set)
fmt.Println("contains e1:", set.Contains(e1))
set.Remove(e1)
fmt.Println("set after removing e1:", set)
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub