Isogram: An alternative

bool UBullCowCartridge::IsIsogram(FString Word) const
{
    std::vector<bool> Letters(26, false);
    for (auto&& Char : Word)
    {
        const int Index = Char - 'A';
        if (Letters[Index])
        {
            return false;
        }
        Letters[Index] = true;
    }
    return true;
}

Assuming you have sanitized the Guess / Word (only kept characters A to Z) and sent it as uppercase (Guess.ToUpper()), this would be an efficient solution.

  1. Declare a placeholder for each possible character (26) and initialize them all to false (as if none of those letters have been seen by default).
  2. Loop each character of the word.
  3. Get the corresponding index in the placeholder by substracting the char with the first possible character (A). e.g. A - A = Index 0, B - A = Index 1, etc.
  4. If the value at position Letters[Index] is true, that means we’ve already seen that letter, so it’s not an Isogram and we can get out immediately.
  5. Otherwise, set the position of Letters[Index] to true to indicate that we’ve seen that letter (the next time we’ll check that position (step #4) we’ll know we’ve seen it already).
  6. We’ve looped all characters of the word, all of them were unique (never returned with false from #4) so it is in fact an isogram, return true.
1 Like

This is a lovely solution @NXGEN. It’s very similar to what I implemented:

// At the top of the file I added this include:
#include <bitset>

bool UBullCowCartridge::IsIsogram(const FString &Word) const
{
    std::bitset<26> LettersSeen;

    for (const auto &Char : Word)
    {
        const auto Position = Char - 'a';
        if (LettersSeen[Position])
        {
            return false;
        }

        LettersSeen.set(Position);
    }

    return true;
}

Some of the differences:

  • Since we aren’t modifying the Word parameter I’m passing it in as a const reference.
  • Char is also not being changed in the ranged for loop, so I also made it a const reference.
  • I’m using a bitset rather than a vector of booleans.
  • Your code assumes a word written in all caps, mine assumes all lowercase.
1 Like

Privacy & Terms