-
Notifications
You must be signed in to change notification settings - Fork 41
/
lcs.go
41 lines (38 loc) · 900 Bytes
/
lcs.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
package jsondiff
// lcs computes the longest common subsequence of two
// slices and returns the index pairs of the LCS, that
// is, the indices into the source and target slices
// where the LCS items are located
func lcs(src, tgt []interface{}) [][2]int {
t := make([][]int, len(src)+1)
for i := 0; i <= len(src); i++ {
t[i] = make([]int, len(tgt)+1)
}
for i := 1; i < len(t); i++ {
for j := 1; j < len(t[i]); j++ {
if deepEqual(src[i-1], tgt[j-1]) {
t[i][j] = t[i-1][j-1] + 1
} else {
t[i][j] = max(t[i-1][j], t[i][j-1])
}
}
}
i, j := len(src), len(tgt)
s := make([][2]int, 0, t[i][j])
for i > 0 && j > 0 {
switch {
case deepEqual(src[i-1], tgt[j-1]):
s = append(s, [2]int{i - 1, j - 1})
i--
j--
case t[i-1][j] > t[i][j-1]:
i--
default:
j--
}
}
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
return s
}