-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlcs_test.go
95 lines (90 loc) · 2.12 KB
/
lcs_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
package diff
import (
"fmt"
"strings"
"testing"
)
func splitLines(s string) (out []Line) {
for i, l := range strings.Split(s, "\n") {
out = append(out, Line{i, strings.TrimSpace(l)})
}
return
}
func TestLCSTable(t *testing.T) {
cases := []struct {
a, b []Line
expectedLengths []int
expectedItems string
}{
{
splitLines("a\nx\nb"),
splitLines("a\nb\nc"),
[]int{0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 2, 2},
` a
- x
b
+ c`,
},
{
splitLines("g\na\nc"),
splitLines("a\ng\nc\na\nt"),
[]int{0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 2, 2, 0, 1, 1, 2, 2, 2},
`+ a
g
+ c
a
+ t
- c`,
},
}
for i, c := range cases {
t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) {
table := NewLCSTable(c.a, c.b)
if len(table.lengths) != len(c.expectedLengths) {
t.Fatalf("LCSTable lengths were not correct:\nexpected: %v\ngot: %v", c.expectedLengths, table.lengths)
}
for i, l := range table.lengths {
if l != c.expectedLengths[i] {
t.Errorf("LCSTable lengths were not correct:\nexpected: %v\ngot: %v", c.expectedLengths, table.lengths)
break
}
}
diff := table.Diff()
diffStr := diffToString(diff)
if diffStr != c.expectedItems {
t.Fatalf("Diff was not correct:\nexpected:\n%v\ngot:\n%v", c.expectedItems, diffStr)
}
})
}
}
func TestLongestCommonSubsequence(t *testing.T) {
cases := []struct {
a, b []Line
expectedLcs [][2]int
}{
{
splitLines("a\nx\nb"),
splitLines("a\nb\nc"),
[][2]int{{0, 0}, {2, 1}},
},
{
splitLines("X\nX\nX\na\nX\nX\nX\nb\nX\nX\nX\nc"),
splitLines("Y\nY\na\nY\nY\nb\nY\nY\nc"),
[][2]int{{3, 2}, {7, 5}, {11, 8}},
},
}
for i, c := range cases {
t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) {
table := NewLCSTable(c.a, c.b)
lcs := table.LongestCommonSubsequence()
if len(lcs) != len(c.expectedLcs) {
t.Fatalf("LCS was not correct:\nexpected:\n%v\ngot:\n%v", c.expectedLcs, lcs)
}
for i := range c.expectedLcs {
if lcs[i] != c.expectedLcs[i] {
t.Fatalf("LCS was not correct:\nexpected:\n%v\ngot:\n%v", c.expectedLcs, lcs)
}
}
})
}
}