-
Notifications
You must be signed in to change notification settings - Fork 0
/
topological_test.go
79 lines (69 loc) · 1.82 KB
/
topological_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package graphs
import (
"fmt"
"os"
"testing"
)
var (
testDataTopoSort = []struct {
name string
initFunc digraphFactoryFunc
}{
{"testDAG1", initDAG1},
}
)
func testTopoSortMethods(t *testing.T, reverse bool, sortFunc func(directedGraph DirectedGraph) ([]int, error)) {
for _, test := range testDataTopoSort {
t.Run(test.name, func(t *testing.T) {
g := test.initFunc()
gSorted, err := sortFunc(g)
var order string
if reverse {
order = "after"
} else {
order = "before"
}
if err != nil {
t.Fatalf("Could not topologically sort the graph %v, error: %v", g, err)
}
// Give the output of the initial and sorted graph
t.Logf("Initial graph: %v\n", g)
t.Logf("Topologically sorted graph: %v\n", gSorted)
// Validate the topological sort
sortedIndex := make([]int, len(gSorted), len(gSorted))
for i, v := range gSorted {
sortedIndex[v] = i
}
for v, edgesFromV := range g.AllEdges() {
for _, w := range edgesFromV {
t.Logf("Vertex [%v] should come %v [%v]... ", v, order, w)
if reverse != (sortedIndex[v] >= sortedIndex[w]) {
t.Logf("Error: topological sort is incorrect")
t.Fail()
}
}
}
})
}
}
func TestTopoSort(t *testing.T) {
testTopoSortMethods(t, false, TopoSort)
}
func TestTopoSortReverse(t *testing.T) {
testTopoSortMethods(t, true, TopoSortReverse)
}
func ExampleTopoSort() {
// Initialize a directed graph from a file
graph, err := LoadDirectedGraph("example/directed_7.txt")
if err != nil {
fmt.Printf("Got an error: %v\n", err)
os.Exit(2)
}
fmt.Printf("Initial graph: %v\n", graph)
// Attempt to topologically sort the graph
if order, err := TopoSort(graph); err != nil {
fmt.Printf("Cannot do topological sort: %v\n", err)
} else {
fmt.Printf("Topologically sorted graph (vertex order): %v\n", order)
}
}