Skip to content

Commit e9558bd

Browse files
implemented the EditDistance dynamic program
1 parent bac583e commit e9558bd

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1,35 @@
11
package algorithms.dynamic
2+
3+
/// Edit Distance Algorithm (Levenshtein Distance)
4+
/// Computes the minimum number of operations (insertions, deletions, and substitutions)
5+
/// required to convert one string into another.
6+
///
7+
/// Time Complexity: O(m * n), where m and n are the lengths of the input strings.
8+
def editDistance(X: Array[Char], Y: Array[Char]): (Array[Array[Int]], Int) = {
9+
10+
val n: Int = Y.length
11+
val m: Int = X.length
12+
13+
val Edit: Array[Array[Int]] = Array.fill(m, n)(0)
14+
15+
for (i <- 0 until n - 1) {
16+
Edit(0)(i) = i
17+
}
18+
for (i <- 0 until m - 1) {
19+
Edit(i)(0) = i
20+
21+
for (j <- 0 until n - 1) {
22+
val ins: Int = Edit(i)(j - 1) + 1
23+
val del: Int = Edit(i - 1)(j) + 1
24+
var rep: Int = Int.MaxValue
25+
if (X(i) == Y(j)) {
26+
rep = Edit(i - 1)(j - 1)
27+
} else {
28+
rep = Edit(i - 1)(j - 1) + 1
29+
}
30+
Edit(i)(j) = Math.min(ins, Math.min(del, rep))
31+
}
32+
33+
}
34+
(Edit, Edit(m - 1)(n - 1))
35+
}

src/main/scala/benchmark/SortingBenchmark.scala

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import org.openjdk.jmh.annotations._
66
import java.util.concurrent.TimeUnit
77
import scala.util.Random
88

9+
// COMMAND : sbt "jmh:run -i 5 -wi 2 -f1 -t1 -rf csv"
10+
911
@BenchmarkMode(Array(Mode.AverageTime))
1012
@OutputTimeUnit(TimeUnit.MILLISECONDS)
1113
@State(Scope.Thread)

0 commit comments

Comments
 (0)