Advertisement
stanevplamen

Levenshtein

Sep 25th, 2022
777
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. exports.getEditDistance = function(a, b){
  2.   if(a.length == 0) return b.length;
  3.   if(b.length == 0) return a.length;
  4.  
  5.   var matrix = [];
  6.  
  7.   // increment along the first column of each row
  8.   var i;
  9.   for(i = 0; i <= b.length; i++){
  10.     matrix[i] = [i];
  11.   }
  12.  
  13.   // increment each column in the first row
  14.   var j;
  15.   for(j = 0; j <= a.length; j++){
  16.     matrix[0][j] = j;
  17.   }
  18.  
  19.   // Fill in the rest of the matrix
  20.   for(i = 1; i <= b.length; i++){
  21.     for(j = 1; j <= a.length; j++){
  22.       if(b.charAt(i-1) == a.charAt(j-1)){
  23.         matrix[i][j] = matrix[i-1][j-1];
  24.       } else {
  25.         matrix[i][j] = Math.min(matrix[i-1][j-1] + 1, // substitution
  26.                                 Math.min(matrix[i][j-1] + 1, // insertion
  27.                                          matrix[i-1][j] + 1)); // deletion
  28.       }
  29.     }
  30.   }
  31.  
  32.   return matrix[b.length][a.length];
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement