Created
July 2, 2012 10:56
-
-
Save wspringer/3032690 to your computer and use it in GitHub Desktop.
Jaro distance in Scala
This file contains 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
import math._ | |
object Jaro { | |
def distance(first: String, second: String) = { | |
val maxLength = max(first.length, second.length) | |
val maxDistance = (maxLength / 2) - 1 | |
var matches = 0 | |
var halfTranspositions = 0 | |
for (i <- 0 until first.length) { | |
val c = first.charAt(i) | |
if (second.length > i && c == second.charAt(i)) matches += 1 | |
else { | |
var found = false | |
for { | |
j <- max(0, i - maxDistance) until min(second.length, i + maxDistance) | |
if !found | |
if (i != j) | |
if (c == second.charAt(j)) | |
} { | |
matches += 1 | |
halfTranspositions += 1 | |
found = true | |
} | |
} | |
} | |
(1.0 / 3.0) * ( | |
(matches / first.length.toDouble) + | |
(matches / second.length.toDouble) + | |
((matches - (halfTranspositions / 2)) / matches.toDouble) | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not so optimized version of Jaro string distance in Scala, but it does the job.