In Python, if you want to check if some element is in a list or array or string or anything, and see if it’s inside another list or array or string or etc, all you really have to do is write
for character in word:
if character in seen:
# do something
This would let you find repeated letters by making a new empty list called something like “Seen”, and loop over your Word (list of Characters). If that Character is in Seen already, then it’s not an isogram. If it isn’t in Seen, then you add it to Seen and move onto the next Character.
But in C++ writing something like that is not so simple haha. But after a lot of Googling I ended up making a couple of functions and writing this to try to get closer to Python.
First we make a function/method to do the equivalent of “if character in seen”:
#include <algorithm>
#include <list>
using namespace std; // Using this is to cut down on having to write std:: everywhere.
/// See if Element is in SearchList.
/// https://stackoverflow.com/questions/24139428/check-if-element-is-in-the-list-contains
bool UBullCowCartridge::Contains(const TCHAR Element, list<TCHAR> SearchList)
{
// Python says "if Element in SearchList". C++ says:
return find(SearchList.begin(), SearchList.end(), Element) != SearchList.end();
}
This searches for the Element provided, from the beginning of SearchList to the end of Searchlist, and checks that it doesn’t equal the end of the Searchlist.
This is the equivalent of writing “If Element in SearchList”, giving us true or false.
Then we can implement it like this:
/// Check if Word is an isogram (does not contain more than 1 of each letter).
bool UBullCowCartridge::IsIsogram(FString Word)
{
// Make empty list "Seen" for keeping track of our letters we're checking.
list<TCHAR> Seen;
// For Character in Word:
for (TCHAR Character: Word) {
// if Character in Seen:
if (Contains(Character, Seen)) {
return false;
}
// Otherwise append Character to the end of Seen list.
Seen.push_back(Character);
}
// Making it here means we went through every Character in Word, and nothing repeated in Seen.
return true;
}
In the end I was happier with reading that, but it did require additional includes, and making a dedicated method “Contains” to make it more readable when it was used in the IsIsogram method.
This might also be slower / more inefficient than the one in the course, I’m not sure to be honest. But working with such tiny words and data, I don’t think it matters. I’m not sure how much these sorts of changes might affect compile time as well. Either way, I just wanted something more familiar and thus more readable to me coming from Python, and it was good practice figuring it out.