new file: sets/stringsUnionFind.go
Go / build (push) Successful in 34s

This commit is contained in:
Acid
2026-07-18 17:34:33 -04:00
parent e54607e9ed
commit 8c73d121e4
3 changed files with 266 additions and 3 deletions
+65
View File
@@ -0,0 +1,65 @@
package sets
// NamedUnionFind{
// unionFind *UnionFind
// index map[string]int
// names []string
// }
type NamedUnionFind struct {
unionFind *UnionFind
index map[string]int
names []string
}
// NewStringsUnion() -> creates a disjoint set from a slice of strings,
// the constructor will deduplicate and return a NamedUnionFind
func NewStringsUnion(params []string) *NamedUnionFind {
namedUnion := &NamedUnionFind{
index: make(map[string]int, len(params)),
}
for _, name := range params {
if _, seen := namedUnion.index[name]; !seen {
namedUnion.index[name] = len(namedUnion.names)
namedUnion.names = append(namedUnion.names, name)
}
}
namedUnion.unionFind = NewUnionFind(len(namedUnion.names))
return namedUnion
}
// Union() -> creates an Union of 2 values, returns true if success
func (n *NamedUnionFind) Union(a, b string) bool {
paramA, ok1 := n.index[a]
paramB, ok2 := n.index[b]
if !ok1 || !ok2 {
return false
}
return n.unionFind.Union(paramA, paramB)
}
// IsUnion() -> returns true if the parameters have the same root
func (n *NamedUnionFind) IsUnion(a, b string) bool {
paramA, ok1 := n.index[a]
paramB, ok2 := n.index[b]
if !ok1 || !ok2 {
return false
}
return n.unionFind.IsUnion(paramA, paramB)
}
// Rep() -> returns the representative name of group, and false if the name is unknown.
func (n *NamedUnionFind) Rep(a string) (string, bool) {
ia, ok := n.index[a]
if !ok {
return "", false
}
return n.names[n.unionFind.Find(ia)], true
}
// Disjointed() -> returns the count of disjointed sets remaining
func (n *NamedUnionFind) Disjointed() int {
return n.unionFind.Disjointed()
}
+8 -3
View File
@@ -1,12 +1,17 @@
package sets
// UnionFind {
// disjointed int
// parent []int
// rank []int
// }
type UnionFind struct {
disjointed int
parent []int
rank []int
}
// NewUnionFind() -> Creates an disjoint set
// NewUnionFind() -> Creates an disjoint set ,takes the unique elements as parameter.
func NewUnionFind(uniqueElements int) *UnionFind {
// counts from 0 correction
uniqueElements += 1
@@ -68,7 +73,7 @@ func (uf *UnionFind) Union(a int, b int) bool {
}
// IsUnion() -> returns true if the parameters have the same root
func (uf UnionFind) IsUnion(a int, b int) bool {
func (uf *UnionFind) IsUnion(a int, b int) bool {
if uf.Find(a) == uf.Find(b) {
return true
}
@@ -76,6 +81,6 @@ func (uf UnionFind) IsUnion(a int, b int) bool {
}
// Disjointed() -> returns the count of disjointed sets remaining
func (uf UnionFind) Disjointed() int {
func (uf *UnionFind) Disjointed() int {
return uf.disjointed
}