utilities.cpp 1.8 KB

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