forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEditDistance.kt
86 lines (72 loc) · 2.13 KB
/
EditDistance.kt
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
package algorithmdesignmanualbook.dynamic
import kotlin.system.measureTimeMillis
import kotlin.test.assertTrue
private fun editDistance(str1: String, str2: String, m: Int, n: Int): Int {
// str2 insertion
if (m == 0) {
return n
}
// str1 insertion
if (n == 0) {
return m
}
// no changes. shift both to lower index for compare
if (str1[m - 1] == str2[n - 1]) {
return editDistance(str1, str2, m - 1, n - 1)
}
return 1 + listOf(
editDistance(str1, str2, m - 1, n), //Insert
editDistance(str1, str2, m, n - 1), // Delete
editDistance(str1, str2, m - 1, n - 1), // Replace
).minOrNull()!!
}
private fun editDistance(str1: String, str2: String, m: Int, n: Int, mem: Array<Array<Int>>): Int {
// str2 insertion
if (m == 0) {
mem[m][n] = n
return n
}
// str1 insertion
if (n == 0) {
mem[m][n] = m
return m
}
// no changes. shift both to lower index for compare
if (str1[m - 1] == str2[n - 1]) {
val distance = editDistance(str1, str2, m - 1, n - 1, mem)
mem[m - 1][n - 1] = distance
return distance
}
val insert = editDistance(str1, str2, m - 1, n, mem)
mem[m - 1][n] = insert
val delete = editDistance(str1, str2, m, n - 1, mem)
mem[m][n - 1] = delete
val replace = editDistance(str1, str2, m - 1, n - 1, mem)
mem[m - 1][n - 1] = replace
return 1 + listOf(
insert, //Insert
delete, // Delete
replace, // Replace
).minOrNull()!!
}
fun main() {
run {
val (str1, str2) = Pair("saturday", "friday")
assertTrue {
editDistance(str1, str2, str1.length, str2.length) == 5
}
}
run {
val (str1, str2) = Pair("saturday", "sunday")
measureTimeMillis {
assertTrue {
editDistance(str1, str2, str1.length, str2.length) == 3
}
}
measureTimeMillis {
assertTrue {
editDistance(str1, str2, str1.length, str2.length, Array(str1.length) { Array(str2.length) { 0 } }) == 3
}
}
}
}