You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.1 KiB
Go

package algo
import (
"testing"
)
func TestFind(t *testing.T) {
subsets := map[string]*Subset{
"a": {parent: "a"},
"b": {parent: "a"},
"c": {parent: "b"},
"d": {parent: "c"},
}
tests := []struct {
name string
subsets map[string]*Subset
element string
expected string
}{
{
name: "element is root",
subsets: subsets,
element: "a",
expected: "a",
},
{
name: "element has parent",
subsets: subsets,
element: "b",
expected: "a",
},
{
name: "element has grandparent",
subsets: subsets,
element: "c",
expected: "a",
},
{
name: "element has great-grandparent",
subsets: subsets,
element: "d",
expected: "a",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := find(tt.subsets, tt.element)
if got != tt.expected {
t.Errorf("find() = %v, want %v", got, tt.expected)
}
})
}
}
func TestUnion(t *testing.T) {
subsets := map[string]*Subset{
"a": {parent: "a"},
"b": {parent: "a"},
"c": {parent: "b"},
"d": {parent: "c"},
}
tests := []struct {
name string
subsets map[string]*Subset
x string
y string
expectedXRoot string
}{
{
name: "x and y are already in the same subset",
subsets: subsets,
x: "a",
y: "b",
expectedXRoot: "a",
},
{
name: "x and y are in different subsets",
subsets: subsets,
x: "b",
y: "c",
expectedXRoot: "a",
},
{
name: "x and y are in different subsets with different ranks",
subsets: subsets,
x: "c",
y: "d",
expectedXRoot: "a",
},
{
name: "x and y are in different subsets with same rank",
subsets: subsets,
x: "a",
y: "d",
expectedXRoot: "a",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Union(tt.subsets, tt.x, tt.y)
got := find(tt.subsets, tt.x)
if got != tt.expectedXRoot {
t.Errorf("Union() failed, got x root = %v, want %v", got, tt.expectedXRoot)
}
})
}
}