Created
March 20, 2012 14:28
-
-
Save akr4/2136168 to your computer and use it in GitHub Desktop.
レーベンシュタイン距離を計算する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Levenshtein { | |
def calc(a: String, b: String): Int = { | |
val d = Array.ofDim[Int](a.size + 1, b.size + 1) | |
// initialization | |
for (i <- 0 to a.size) d(i)(0) = i | |
for (j <- 0 to b.size) d(0)(j) = j | |
for ( | |
i <- 1 to a.size; | |
j <- 1 to b.size | |
) { | |
d(i)(j) = List( | |
d(i - 1)(j) + 1, | |
d(i)(j - 1) + 1, | |
d(i - 1)(j - 1) + (if (a(i - 1) == b(j - 1)) 0 else 2) | |
).min | |
} | |
printTable(a, b, d) | |
d(a.size)(b.size) | |
} | |
def printTable(a: String, b: String, d: Array[Array[Int]]) { | |
for ( | |
i <- 0 to a.size reverse; | |
row = d(i) | |
) { | |
print("%2s ".format(("#" + a)(i))) | |
println(row.map("%2d".format(_)).mkString(" ")) | |
} | |
println((" #" + b).map("%2s".format(_)).mkString(" ")) | |
} | |
} |
Author
akr4
commented
Mar 20, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment