BullCowGame: Loop in IsIsogram function doesn't check Word[2] and Word[3]

This is the function I wrote.
If the Input is “hell” the function returns false, as expected.
if the Input is “hello” the function returns true, this is not ideal.
I presume the problem is somewhere betweenthe position [2] and [3].

I wrote the code myself then compared to the one written by Mike. It’s practically the same if I’m not mistaken.
What is the problem?

bool UBullCowCartridge::IsIsogram(FString Word) const {

	int32 Index;
	int32 Compare;

	for (Index = 0; Index < Word.Len(); Index++) 
	{
		for (Compare = Index + 1; Compare < Word.Len(); Compare++)
		{
			if (Word[Index] == Word[Compare]) 
			{
				PrintLine(TEXT("false"));  //debug line
			        return false;
			}
		}
	}
	return true;
}

The initialiser part of a for loop is only done once at the beginning. So your loop is doing

Index = 0, Compare = 1
Index = 0, Compare = 2
Index = 0, Compare = 3
Index = 0, Compare = 4
Index = 0, Compare = 5

Index = 1, Compare = 5 # doesn't enter inner for loop
Index = 2, Compare = 5 # doesn't enter inner for loop
Index = 3, Compare = 5 # doesn't enter inner for loop
Index = 4, Compare = 5 # doesn't enter inner for loop
Index = 5, Compare = 5 # doesn't enter inner for loop
# exit outer loop
# return true

With Index and Compare being initialised within the for loop (which is best practice). You wouldn’t have this issue as once the inner loop ends, Compare would go out of scope and re-initialised to Index + 1 on the next loop of Index meaning that loop would go

Index = 0, Compare = 1
Index = 0, Compare = 2
Index = 0, Compare = 3
Index = 0, Compare = 4
Index = 0, Compare = 5

Index = 1, Compare = 2
Index = 1, Compare = 3
Index = 1, Compare = 4
Index = 1, Compare = 5

Index = 2, Compare = 3 # l == l return false
# how it would continue if it didn't
Index = 2, Compare = 4
Index = 2, Compare = 5

Index = 3, Compare = 4
Index = 3, Compare = 5

Index = 4, Compare = 5

Hi Dan thank you for the support!
Had a pretty busy week, I’m sorry that I didn’t catch up sooner.

So, I found the mistake, I nested the isisogram function inside an if condition to compare the word and the guess lenght. When the word and the guess had the same lenght, the function isisogram never occurred. Here’s the mess:

if (Guess.Len() != HiddenWord.Len())

            {

                if (IsIsogram(Guess) != true) {

                    PrintLine(TEXT("Not an isogram"));

                }

                PrintLine(TEXT("\nThe word is %i characters long, not %i!"), HiddenWord.Len(), Guess.Len());

            }
1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms