Last active
August 29, 2015 14:01
-
-
Save dbalduini/468934d87e95cbf30697 to your computer and use it in GitHub Desktop.
Levenshtein Distance Algorithm
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
// The straightforward, but very slow version | |
def levenshteinDistance(a: String, b: String): Int = { | |
val aLen = a.length | |
val bLen = b.length | |
def minimum(x: Int, y: Int, z: Int) = Math.min(Math.min(x, y), z) | |
def max(i: String, j: String) = if (i >= j) i else j | |
def min(i: String, j: String) = if (i <= j) i else j | |
def cost = if (aLen - 1 == bLen - 1) 0 else 1 | |
if (min(a, b).length == 0) max(a, b).length | |
else minimum( | |
levenshteinDistance(a.dropRight(1), b) + 1, | |
levenshteinDistance(a, b.dropRight(1)) + 1, | |
levenshteinDistance(a.dropRight(1), b.dropRight(1)) + cost | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment