fork(10) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Protsyk.Toolkit.Levenshtein {
  7. class Program {
  8.  
  9. static double WeightedLevenshtein(string b1, string b2) {
  10. b1 = b1.ToUpper();
  11. b2 = b2.ToUpper();
  12.  
  13. double[,] matrix = new double[b1.Length + 1, b2.Length + 1];
  14.  
  15. for (int i = 1; i <= b1.Length; i++) {
  16. matrix[i, 0] = i;
  17. }
  18.  
  19. for (int i = 1; i <= b2.Length; i++) {
  20. matrix[0, i] = i;
  21. }
  22.  
  23. for (int i = 1; i <= b1.Length; i++) {
  24. for (int j = 1; j <= b2.Length; j++) {
  25. double distance_replace = matrix[(i - 1), (j - 1)];
  26. if (b1[i - 1] != b2[j - 1]) {
  27. // Cost of replace
  28. distance_replace += Math.Abs((float)(b1[i - 1]) - b2[j - 1]) / ('Z'-'A');
  29. }
  30.  
  31. // Cost of remove = 1
  32. double distance_remove = matrix[(i - 1), j] + 1;
  33. // Cost of add = 1
  34. double distance_add = matrix[i, (j - 1)] + 1;
  35.  
  36. matrix[i, j] = Math.Min(distance_replace,
  37. Math.Min(distance_add, distance_remove));
  38. }
  39. }
  40.  
  41. return matrix[b1.Length, b2.Length] ;
  42. }
  43.  
  44. static void Main(string[] args) {
  45. double w1 = WeightedLevenshtein("THEATRE", "TNEATRE");
  46. double w2 = WeightedLevenshtein("THEATRE", "TOEATRE");
  47.  
  48. Console.WriteLine("Distance between THEATRE and TNEATRE is: " + w1);
  49. Console.WriteLine("Distance between THEATRE and TOEATRE is: " + w2);
  50. }
  51. }
  52. }
Success #stdin #stdout 0.03s 37016KB
stdin
Standard input is empty
stdout
Distance between THEATRE and TNEATRE is: 0.24
Distance between THEATRE and TOEATRE is: 0.28