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;
            }
        }
    }
4 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.

2 Likes

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.

1 Like

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;
    }

@SilentObserver

I’m a beginner with C++ so I may be wrong, but doesn’t usedChars.find(inputChar) actually iterate through usedChars? making it the computational equivalent of a second loop?
basically, if I’m getting it right, it reverses the second loop in a sense (does increasingly more iterations instead of increasingly less), ending up with the same total complexity as the nested for loops. but thanks for the C++ syntax study opportunity :smiley: (all that iterator stuff is something was completely unfamiliar with, until pretty much now)

@Savigo

came here to write the same thing myself and found your post. I think this should be added into the course, since with that change the code actually reflects the logic that was initially presented (the rows&columns thing).

Privacy & Terms