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