Small change to lower the number of iterations

I decided to add “- 1” in condition of the 1st for loop, since we only have to compare “Index” to “Comparison” until Index is equal to Word.Len() - 2 (we don’t have to compare the same positions).
Do I think correctly?
I’ve tested my code and it works fine, but I’m not sure if that’s a good practice.

for (int32 Index = 0; Index < Word.Len() - 1; Index++)
    {
        for (int32 Comparison = Index + 1; Comparison < Word.Len(); Comparison++)
        {
            if (Word[Index] == Word[Comparison])
            {
                return false;
            }
        }
    }
2 Likes

Your logic seems to me to be correct, and given that in the lecture Mike made a point of showing the table of comparisons and demonstrating that you don’t need to compare beyond an index of 3, I am a bit surprised that he didn’t do it your way. Both ways work since the inner loop is never executed if the index is greater than 3. The difference is that your solution stops when the index becomes 4 (due to it being incremented at the end of the outer loop), whereas the solution on the course allows index to be both 4 and 5 before the outer loop is terminated. So your solution misses an extra inner loop step, which is marginally more efficient. I suppose that in some ways the course solution might be a little easier to read as you don’t have to worry about why you are comparing index with Word.Len() -1.

1 Like

That is exactly the same result that i came up with, using the same logic as you.
I thought I may have done something wrong, but tested thoroughly and everything seems to work OK.

If you really want to get fancy you don’t need an second loop at all

bool isIsoGram(const FString& Input) {
        std::set<TCHAR> usedChars;
        for (TCHAR inputChar : Input) {
            if (usedChars.find(inputChar) != usedChars.end()) {
                return false;
            }
            usedChars.insert(inputChar);
        }
        return true;
    }