vendor/github.com/ysmood/got/lib/lcs/utils.go
64 lines · 1182 bytes
1package lcs
2
3import (
4 "strings"
5)
6
7func min(x, y int) int {
8 if x < y {
9 return x
10 }
11 return y
12}
13
14func eq(x, y Comparable) bool {
15 return x.String() == y.String()
16}
17
18// String interface
19func (xs Sequence) String() string {
20 if len(xs) == 0 {
21 return ""
22 }
23
24 l := 0
25 for _, el := range xs {
26 l += len(el.String())
27 }
28 if l == len(xs) {
29 out := ""
30 for _, c := range xs {
31 out += c.String()
32 }
33 return out
34 }
35
36 out := []string{}
37 for _, c := range xs {
38 out = append(out, c.String())
39 }
40 return strings.Join(out, "\n")
41}
42
43// StandardLCS implementation for testing purpose only, because it's very inefficient.
44// https://en.wikipedia.org/wiki/Longest_common_subsequence_problem#LCS_function_defined.
45func StandardLCS(xs, ys Sequence) Sequence {
46 last := func(s Sequence) Comparable {
47 return s[len(s)-1]
48 }
49 noLast := func(s Sequence) Sequence {
50 return s[:len(s)-1]
51 }
52
53 if len(xs)*len(ys) == 0 {
54 return Sequence{}
55 } else if last(xs).String() == last(ys).String() {
56 return append(StandardLCS(noLast(xs), noLast(ys)), last(xs))
57 }
58
59 left, right := StandardLCS(xs, noLast(ys)), StandardLCS(noLast(xs), ys)
60 if len(left) > len(right) {
61 return left
62 }
63 return right
64}