Levenshtein 距离的nodejs实现

var math = require('math');

function twoDimensionalArray(xMax, yMax) {
var arr = new Array()
for (var i=0; i arr[i] = new Array();
for (var j=0; j arr[i][j] = i + j;
}
}
return arr;
}

var str1 = '我是一个人';
var str2 = '我是一个好人';
str1_length = str1.length;
str2_length = str2.length;

console.log(str1_length);
console.log(str2_length);

var arr = twoDimensionalArray(str1_length+1, str2_length+1);
//console.log(arr);

var temp = null;

for (var i = 1; i <= str1_length; i++) {

for (var  j = 1; j <= str2_length; j++) {  
    if (str1.charAt(i - 1) == str2.charAt(j - 1)) {  
        temp = 0;  
    } else {  
        temp = 1;  
    }  
    
    //console.log(arr[i - 1][j - 1] + temp);
    //console.log(j);
    //console.log(arr[i][j - 1] + 1);
    //console.log(arr[i - 1][j] + 1);
    arr[i][j] = math.min(arr[i - 1][j - 1] + temp, arr[i][j - 1] + 1,  arr[i - 1][j] + 1);  


}  

}

var similarity =1 - arr[str1_length][str2_length] / math.max(str1_length, str2_length);

console.log(similarity);

你可能感兴趣的:(Levenshtein 距离的nodejs实现)