我怎样才能最好地对这个Go Disjoint Sets数据结构进行类型化处理?

时间:2013-09-12 02:50:03

标签: go

我有一个DisjointSets数据结构(从Cormen中提取),在Go中使用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))
}

我想尽可能少地编写增量代码,以便为float64string等使用此结构。我该怎么做?

到目前为止我尝试了什么

我已经阅读了有关Interfaces的所有内容,但我似乎并不了解如何应用它而无需为每种类型编写完整的实现。

3 个答案:

答案 0 :(得分:1)

Go没有模板,所以我认为没有一种优雅的方法可以做到这一点。您可以尝试更改类以使用interface{}而不是int64。

答案 1 :(得分:1)

使用界面时遇到的问题是什么?您应该能够轻松地将该代码转换为使用interface{}作为元素类型,并使其适用于为其定义了相等的任何类型(可以work as map keys)。

有些事情:

答案 2 :(得分:0)

看起来你正在尝试实现经典的union-find算法。

为什么你不能保留你所拥有的东西,只需将你想要的任何东西(float64string等)映射到{{1 }}?那么您根本不需要更改原始代码。想想作文。

具体而言,从您想要的任何域添加地图,例如int64

string

然后,每当你想弄清楚它属于哪个集合时,使用var m1 map[string]int64 ... m1["hello"] = 0 m2["world"] = 1 从字符串转到元素的整数表示,然后使用原始代码找到父代表。