More Efficient IsIsogram Function

Hi so just a disclaimer that since there’s only 5 characters in our words it’s not a huge jump in performance. But if you looked at the example code and thought “I shouldn’t have to loop through this array more than once.” You were right.

You can take advantage of hash sets, in C++ called “unordered sets” that store references to all the characters you’ve seen, and if you seen one more than once, you can return false… here’s my implementation.

    unordered_set<TCHAR> HashSet;
    FString LowerCaseWord = Word.ToLower();
    for (int i=0; i<LowerCaseWord.Len(); i++) {
        if (HashSet.find(LowerCaseWord[i])==HashSet.end()) {
            HashSet.insert(LowerCaseWord[i]);
        } else {
            return false;
        }
    }

    return true;

Note: you’ll have to also add

#include <unordered_set>

to get this to work, hope it helps!

After learning that it’s better to use unreal’s version of types so that its compatible with all platforms, I’ve updated it to use Unreal’s TSet

    TSet<TCHAR> HashSet;
    FString LowerCaseWord = Word.ToLower();
    for (int i=0; i<LowerCaseWord.Len(); i++) {
        if (!HashSet.Contains(LowerCaseWord[i])) {
            HashSet.Add(LowerCaseWord[i]);
        } else {
            return false;
        }
    }

    return true;

and the include is

#include "Containers/Set.h"

Documentation is here: TSet | Unreal Engine Documentation

Hey, you don’t have to use Contains, you can pass a bool pointer to Add as a 2nd parameter to check if the element is already in the set
Take a look at my version

1 Like

Privacy & Terms