Advertisement
Guest User

Untitled

a guest
Oct 10th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1.         public static string ClosestEntry(this IList<string> list, string toMatch)
  2.         {
  3.             string outStr = String.Empty;
  4.  
  5.             outStr = list.Aggregate((c, d) => c.LevenshteinDistance(toMatch) < d.LevenshteinDistance(toMatch) ? c : d);
  6.  
  7.             return outStr;
  8.         }
  9.  
  10.         public static IList<string> SortedByFamiliarity(this IList<string> list, string toMatch)
  11.         {
  12.             var outList = new List<string>();
  13.  
  14.             outList = list.OrderBy(x => LevenshteinDistance(x, toMatch)).ToList();
  15.  
  16.             return outList;
  17.         }
  18.  
  19.         public static int LevenshteinDistance(this string source, string target)
  20.         {
  21.             if (String.IsNullOrEmpty(source))
  22.             {
  23.                 if (String.IsNullOrEmpty(target)) return 0;
  24.                 return target.Length;
  25.             }
  26.             if (String.IsNullOrEmpty(target)) return source.Length;
  27.  
  28.             if (source.Length > target.Length)
  29.             {
  30.                 var temp = target;
  31.                 target = source;
  32.                 source = temp;
  33.             }
  34.  
  35.             var m = target.Length;
  36.             var n = source.Length;
  37.             var distance = new int[2, m + 1];
  38.             // Initialize the distance 'matrix'
  39.             for (var j = 1; j <= m; j++) distance[0, j] = j;
  40.  
  41.             var currentRow = 0;
  42.             for (var i = 1; i <= n; ++i)
  43.             {
  44.                 currentRow = i & 1;
  45.                 distance[currentRow, 0] = i;
  46.                 var previousRow = currentRow ^ 1;
  47.                 for (var j = 1; j <= m; j++)
  48.                 {
  49.                     var cost = (target[j - 1] == source[i - 1] ? 0 : 1);
  50.                     distance[currentRow, j] = Math.Min(Math.Min(
  51.                             distance[previousRow, j] + 1,
  52.                             distance[currentRow, j - 1] + 1),
  53.                         distance[previousRow, j - 1] + cost);
  54.                 }
  55.             }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement