When we started the work in this section, we were trying to write a test to handle the scenario where the second letter duplicates the first letter. That triggered us to make our algorithm case-insensitive. We can now return to our original goal and write this test:
c2/36/SoundexTest.cpp | |
| TEST_F(SoundexEncoding, CombinesDuplicateCodesWhen2ndLetterDuplicates1st) { |
| ASSERT_THAT(soundex.encode("Bbcd"), Eq("B230")); |
| } |
Our solution involves a little bit of change to the overall policy embodied in encode. We pass the entire word to encodedDigits for encoding so that we can compare the encoding of the second letter to the first. We append only the tail of all encoded digits to the overall encoding.
In encodedDigits, we encode the word’s first character so that comparisons to the prior digit can compare against it. Since encodedDigits now encodes the entire word, we alter isComplete to accommodate one more character. We also change the core loop in encodedDigits to iterate across the tail of the word.
c2/36/Soundex.h | |
| std::string encode(const std::string& word) const { |
* | return zeroPad(upperFront(head(word)) + tail(encodedDigits(word))); |
| } |
| |
| std::string encodedDigits(const std::string& word) const { |
| std::string encoding; |
| |
* | encoding += encodedDigit(word.front()); |
| |
* | for (auto letter: tail(word)) { |
| if (isComplete(encoding)) break; |
| |
| auto digit = encodedDigit(letter); |
| if (digit != NotADigit && digit != lastDigit(encoding)) |
| encoding += digit; |
| } |
| return encoding; |
| } |
| |
| bool isComplete (const std::string& encoding) const { |
* | return encoding.length() == MaxCodeLength; |
| } |
3.147.85.221