levenshteinMatrice.hpp 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. #pragma once
  2. #include "levenshtein.hpp"
  3. enum eLevenshteinOperator: char
  4. {
  5. add = '+',
  6. rem = '-',
  7. mod = '!',
  8. equ = '='
  9. };
  10. class LevenshteinMatrice_base
  11. {
  12. public:
  13. virtual ~LevenshteinMatrice_base() {}
  14. virtual void prune() =0;
  15. };
  16. template<typename T>
  17. class LevenshteinMatrice: public LevenshteinMatrice_base
  18. {
  19. public:
  20. LevenshteinMatrice(size_t n, size_t m)
  21. {
  22. this->n = n;
  23. this->m = m;
  24. this->matrice = new T*[n +1]();
  25. this->subMatrice = new LevenshteinMatrice_base**[n +1]();
  26. matrice[0] = new T[m +1];
  27. for (size_t i =1; i <= m; ++i)
  28. matrice[0][i] = i;
  29. for (size_t i=1; i <= n; ++i)
  30. {
  31. matrice[i] = new T[m +1];
  32. matrice[i][0] = i;
  33. }
  34. for (size_t i=0; i <= n; ++i)
  35. {
  36. subMatrice[i] = new LevenshteinMatrice_base*[m +1];
  37. for (size_t j=0; j <= m; ++j)
  38. subMatrice[i][j] = nullptr;
  39. }
  40. };
  41. ~LevenshteinMatrice()
  42. {
  43. for (size_t i=0; i <= n; ++i)
  44. {
  45. delete []matrice[i];
  46. for (size_t j=0; j <= m; ++j)
  47. if (subMatrice[i][j])
  48. delete subMatrice[i][j];
  49. delete []subMatrice[i];
  50. }
  51. delete []matrice;
  52. delete []subMatrice;
  53. };
  54. void prune()
  55. {
  56. //TODO
  57. }
  58. T get(size_t a, size_t b) const
  59. {
  60. return matrice[a][b];
  61. };
  62. void set(size_t a, size_t b, T value, LevenshteinMatrice_base *subMatrice =nullptr)
  63. {
  64. matrice[a][b] = value;
  65. this->subMatrice[a][b] = subMatrice;
  66. };
  67. std::list<eLevenshteinOperator> shortestPath() const
  68. {
  69. std::list<eLevenshteinOperator> result;
  70. size_t i = n;
  71. size_t j = m;
  72. while (i || j)
  73. {
  74. if (i && (!j || matrice[i][j] > matrice[i-1][j]))
  75. {
  76. result.push_front(eLevenshteinOperator::add);
  77. --i;
  78. }
  79. else if (j && (!i || matrice[i][j] > matrice[i][j -1]))
  80. {
  81. result.push_front(eLevenshteinOperator::rem);
  82. --j;
  83. }
  84. else if (i && j)
  85. {
  86. result.push_front(matrice[i][j] == matrice[i-1][j-1] ? eLevenshteinOperator::equ : eLevenshteinOperator::mod);
  87. --i;
  88. --j;
  89. }
  90. else if (i)
  91. {
  92. result.push_front(eLevenshteinOperator::add);
  93. --i;
  94. }
  95. else if (j)
  96. {
  97. result.push_front(eLevenshteinOperator::rem);
  98. --j;
  99. }
  100. }
  101. return result;
  102. }
  103. T result() const
  104. {
  105. return matrice[n][m];
  106. };
  107. private:
  108. T **matrice;
  109. LevenshteinMatrice_base ***subMatrice;
  110. size_t n;
  111. size_t m;
  112. };