I have a test where I have to validate the order of items in a List based on a pre-defined hierarchy that is being given to me as part of my assignment. Here it is below.
- Cat
- Dog
- Horse
- Elephant
The items in the list would only ever be those four types, but the size of list is not limited. The list will be passed in as part of the method. There can be multiple of each or none at all. The below two list would be valid:
- Cat
- Cat
- Dog
- Elephant
This would not.
- Elephant
- Dog
- Horse
- Cat
Below is what I have so far, and I feel as though there is a much more elegant solution. In particular, I would like to minimize the amount of bools and if statements I am using.
public bool ValidateAnimalOrder(List<string> listOfAnimals)
{
bool catExists = false;
bool dogExists = false;
bool horseExists = false;
bool elephantExists = false;
for (int x = 0; x < listOfAnimals.Count; x++)
{
if (listOfAnimals[x] == "Cat")
{
catExists = true;
if(dogExists || horseExists || elephantExists)
{
return false;
}
}
if (listOfAnimals[x] == "Dog")
{
dogExists = true;
if (horseExists || elephantExists)
{
return false;
}
}
if (listOfAnimals[x] == "Horse")
{
horseExists = true;
if (elephantExists)
{
return false;
}
}
if (listOfAnimals[x] == "Elephant")
{
elephantExists = true;
}
}
return true;
}