-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathld.go
More file actions
63 lines (50 loc) · 1.24 KB
/
Copy pathld.go
File metadata and controls
63 lines (50 loc) · 1.24 KB
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
package main
import (
"strings"
"unicode/utf8"
)
// IgnoreIndentation drops the whitespace that only lays a snippet out — the
// spaces and tabs around every line, and blank lines altogether — so that a
// code answer typed at a different indentation still comes out at distance 0.
func IgnoreIndentation(text string) string {
lines := []string{}
for line := range strings.SplitSeq(text, "\n") {
line = strings.Trim(line, " \t\r")
if line == "" {
continue
}
lines = append(lines, line)
}
return strings.Join(lines, "\n")
}
func Ld(actual, expected string) (distance int) {
m, n := utf8.RuneCountInString(expected)+1, utf8.RuneCountInString(actual)+1
arr := make([][]int, m)
for i := range arr {
arr[i] = make([]int, n)
}
for i := range arr {
for j := range arr[i] {
distance := calcNextCell(i, j, arr, actual, expected)
arr[i][j] = distance
}
}
return arr[m-1][n-1]
}
func calcNextCell(i, j int, arr [][]int, actual, expected string) int {
if i == 0 && j == 0 {
return 0
}
if i == 0 {
return arr[i][j-1] + 1
}
if j == 0 {
return arr[i-1][j] + 1
}
eR := []rune(expected)[i-1]
aR := []rune(actual)[j-1]
if eR == aR {
return arr[i-1][j-1]
}
return min(arr[i][j-1], arr[i-1][j-1], arr[i-1][j]) + 1
}