I have a DisjointSets data structure (pulled from Cormen), implemented in Go to work with int64
.
type DisjointSets struct {
ranks map[int64]int64
p map[int64]int64
}
// New returns a new DisjointSets
func NewDisjointSets() *DisjointSets {
d := DisjointSets{map[int64]int64{}, map[int64]int64{}}
return &d
}
// MakeSet adds element x to the disjoint sets in its own set
func (d *DisjointSets) MakeSet(x int64) {
d.p[x] = x
d.ranks[x] = 0
}
// Link assigns x to y or vice versa, depending on the rank of each
func (d *DisjointSets) Link(x, y int64) {
if d.ranks[x] > d.ranks[y] {
d.p[y] = x
} else {
d.p[x] = y
if d.ranks[x] == d.ranks[y] {
d.ranks[y] += 1
}
}
}
// FindSet returns the set in which an element x sits
func (d *DisjointSets) FindSet(x int64) int64 {
if x != d.p[x] {
d.p[x] = d.FindSet(d.p[x])
}
return d.p[x]
}
// Union combines two elements x and y into one set.
func (d *DisjointSets) Union(x, y int64) {
d.Link(d.FindSet(x), d.FindSet(y))
}
I'd like to write as little incremental code as possible to use this structure for float64
, string
, etc. How do I do this?
What I've tried so far
I've read everything I can about Interfaces, but I just don't seem to understand how to apply it without having to write a complete implementation for each type.