Created
April 29, 2015 23:37
-
-
Save thushan/48527fa7a642fc21813c to your computer and use it in GitHub Desktop.
Levenshtein distance calculation between two words. See http://en.wikipedia.org/wiki/Levenshtein_distance
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
let levenshtein word1 word2 = | |
let preprocess = fun (str : string) -> str.ToLower().ToCharArray() | |
let chars1, chars2 = preprocess word1, preprocess word2 | |
let m, n = chars1.Length, chars2.Length | |
let table : int[,] = Array2D.zeroCreate (m + 1) (n + 1) | |
for i in 0..m do | |
for j in 0..n do | |
match i, j with | |
| i, 0 -> table.[i, j] <- i | |
| 0, j -> table.[i, j] <- j | |
| _, _ -> | |
let delete = table.[i-1, j] + 1 | |
let insert = table.[i, j-1] + 1 | |
let substitute = | |
if chars1.[i - 1] = chars2.[j - 1] | |
then table.[i-1, j-1] | |
else table.[i-1, j-1] + 2 | |
table.[i, j] <- List.min [delete; insert; substitute] | |
table.[m, n], table | |
$ levenshtein "Tarragindi" "Holland Park" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment