-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathfloydwarshall_test.go
110 lines (100 loc) · 2.16 KB
/
floydwarshall_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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package graph
import (
"math"
"testing"
)
const float64EqualityThreshold = 1e-9
// almostEqual subtracts two float64 variables and returns true if they differ less then float64EqualityThreshold
// reference: https://stackoverflow.com/a/47969546
func almostEqual(a, b float64) bool {
return math.Abs(a-b) <= float64EqualityThreshold
}
// IsAlmostEqualTo verifies if two WeightedGraphs can be considered almost equal
func (a *WeightedGraph) IsAlmostEqualTo(b WeightedGraph) bool {
if len(*a) != len(b) {
return false
}
for i := range *a {
if len((*a)[i]) != len(b[i]) {
return false
}
for j := range (*a)[i] {
if (*a)[i][j] == Inf && b[i][j] == Inf {
continue
}
if !almostEqual((*a)[i][j], b[i][j]) {
return false
}
}
}
return true
}
func TestFloydWarshall(t *testing.T) {
var floydWarshallTestData = []struct {
description string
graph [][]float64
expected [][]float64
}{
{
description: "test empty graph",
graph: nil,
expected: nil,
},
{
description: "test graph with wrong dimensions",
graph: [][]float64{
{1, 2},
{Inf},
},
expected: nil,
},
{
description: "test graph with no edges",
graph: [][]float64{
{Inf, Inf},
{Inf, Inf},
},
expected: [][]float64{
{Inf, Inf},
{Inf, Inf},
},
},
{
description: "test graph with only negative edges",
graph: [][]float64{
{-3, -2},
{-3, -2},
},
expected: [][]float64{
{-17, -25},
{-26, -34},
},
},
{
description: "test graph with 5 vertices and self-loops",
graph: [][]float64{
{1, 2, Inf, Inf, Inf},
{Inf, Inf, 3, -4, Inf},
{Inf, Inf, Inf, Inf, 5},
{1, Inf, Inf, Inf, Inf},
{Inf, Inf, Inf, 2, Inf},
},
expected: [][]float64{
{-1, 1, 4, -3, 8},
{-3, -1, 2, -5, 6},
{7, 9, 12, 5, 5},
{0, 2, 5, -2, 9},
{2, 4, 7, 0, 9},
},
},
}
for _, test := range floydWarshallTestData {
t.Run(test.description, func(t *testing.T) {
result := FloydWarshall(test.graph)
if !result.IsAlmostEqualTo(test.expected) {
t.Logf("FAIL: %s", test.description)
t.Fatalf("Expected result:%f\nFound: %f", test.expected, result)
}
})
}
}