code.cpp 1.1 KB

12345678910111213141516171819202122232425
  1. /* Given two words, the letter distance is calculated by taking the absolute
  2. * value of the difference in character codes and summing up the difference.
  3. * If one word is longer than another, add the difference in lengths
  4. * towards the score.
  5. * To illustrate:letterDistance("house", "fly") = dist("h", "f") + dist("o", "l") + dist("u", "y") + dist(house.length, fly.length)
  6. * = |104 - 102| + |111 - 108| + |117 - 121| + |5 - 3|
  7. * = 2 + 3 + 4 + 2
  8. * = 11
  9. * Always start comparing the two strings from their first letter.
  10. * Excess letters are not counted towards distance.
  11. * Capital letters are included.
  12. */
  13. int letterDistance(std::string str1, std::string str2) {
  14. // find the smaller string length
  15. int min = (str1.size()<str2.size()) ? str1.size() : str2.size();
  16. int total = 0;
  17. // sum of difference between strings character codes and accumulate
  18. for(int i=0;i<min;i++){
  19. int strDiff = str1[i] - str2[i];
  20. total += abs(strDiff);
  21. }
  22. // add the difference in length, if one word is longer than the other
  23. return total+abs(str1.size()-str2.size());
  24. }