I have an array of strings (4 in the array) which acts as names for drug ingredients for a drug system I’m working on.
The drug system uses labs which holds up to 5 ingredients to mix at once. I need to check to see if the combination matches one that I give it.
For example:
I’m trying to see if the drug lab has the following ingredients with no duplicates.
“Coca leaves”, “Trimethylpentane”, “Ammonia” and “Sulfuric Acid”.
How can I do this, again… checking the names against the strings in the array.
–
Disclaimer: This isn’t a system for an OOL, so unfortunately I can’t use Objects otherwise I would.
So you have a string array that contains your recipe, like “Ingredient A”, “Ingredient B”, “Ingredient C”.
Then you have a variable string array that you want to check whether it is the same as the recipe, but:
the order doesn’t matter
duplicates are not allowed
are extras allowed?
One simple method I can think of is this:
Make a copy of the variable string array, lets call it ContentsCopy.
Iterate over all strings ‘IngredientName’ in the recipe array, call ContentsCopy.RemoveSingle(IngredientName). If RemoveSingle returned 0, the ingredient was not present, meaning the check failed. We’re done, abort.
After iterating if RemoveSingle never returned 0, check if ContentsCopy is empty. If it is, then the contents exactly matched your recipe.
I’ll offer an alternative to the string check (not sure if it’s valid or not).
Rather than doing string compares against 4 other strings, I’d simply sort the ingredients, append them into one large string, and then just hash that string to get a simple uint32 that could be used as a key into a map that contains all the valid recipes.
e.g.
TMap<uint32, FString> HashToRecipeMap; // All known recipes and their incredients.
// Load up all valid recipes.
void InitializeRecipeMap()
{
// For each Recipe you have, do the following:
FString RecipeName = "Some Recipe";
// Read in the incredients into a TArray<FString>.
TArray<FString> Ingredients;
HashToRecipeMap[GetRecipeHash(Ingredients)] = RecipeName;
}
// Create a hash based on the ingredients passed in.
void GetRecipeHash(const TArray<FString>& ingredients) const
{
// You could possibly move this sort outside of the function, just depends on who you want to be responsible for the sort.
TArray<FString> SortedArray(ingredients);
SortedArray.Sort();
FString hashString;
// Build up a string that is just all the ingredients concatentated together alphabetically.
for each (FString ingredient in SortedArray)
{
hashString.Append(ingredient);
}
return GetTypeHash(hashString);
}
// Check to see if we can make something with the ingredients selected.
bool IsValidRecipe(const TArray<FString>& ingredients) const
{
return HashToRecipeMap.Contains(GetRecipeHash(ingredients));
}