utilities.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "utilities.hpp"
  2. #include <chrono>
  3. #include <string>
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <numeric> //iota
  7. struct cScopeTimer::sPimpl {
  8. std::chrono::steady_clock::time_point start;
  9. std::chrono::steady_clock::time_point end;
  10. sPimpl()
  11. {
  12. start = std::chrono::steady_clock::now();
  13. }
  14. ~sPimpl(){
  15. end = std::chrono::steady_clock::now();
  16. std::chrono::microseconds diff = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
  17. std::cout << " took=" << diff.count() << "ms !\n";
  18. }
  19. };
  20. cScopeTimer::cScopeTimer()
  21. : aPimpl(new sPimpl())
  22. {}
  23. /**
  24. * Calculates the Levenshtein distance of two strings.
  25. * @author http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#C.2B.2B
  26. * comparison test was done here http://cpp.sh/2o7w
  27. */
  28. int levenshtein(const std::string &s1, const std::string &s2)
  29. {
  30. // To change the type this function manipulates and returns, change
  31. // the return type and the types of the two variables below.
  32. int s1len = static_cast<int>(s1.size());
  33. int s2len = static_cast<int>(s2.size());
  34. auto column_start = (decltype(s1len))1;
  35. auto column = new decltype(s1len)[s1len + 1];
  36. std::iota(column + column_start, column + s1len + 1, column_start);
  37. for (auto x = column_start; x <= s2len; x++) {
  38. column[0] = x;
  39. auto last_diagonal = x - column_start;
  40. for (auto y = column_start; y <= s1len; y++) {
  41. auto old_diagonal = column[y];
  42. auto possibilities = {
  43. column[y] + 1,
  44. column[y - 1] + 1,
  45. last_diagonal + (s1[y - 1] == s2[x - 1]? 0 : 1)
  46. };
  47. column[y] = std::min(possibilities);
  48. last_diagonal = old_diagonal;
  49. }
  50. }
  51. auto result = column[s1len];
  52. delete[] column;
  53. return result;
  54. }