Let’s assume I have the following array:
string[] arr = ["Off", "Off", "Off", "Duty", "Off", "Off", "Duty", "Duty", "Duty", "Duty", "Off", "Off", "Duty"];
I want to check if the array has the two or more “Off”, then followed by a “Duty”, then followed by two or more “Off”.
Currently, I am doing a loop, checking if the value is “Duty”, then going back two values and check if both are “Off”, then going forward and check if next two are “Off”. It works, but I feel it can be better:
for (int i = 0; i < roster.Length; i++)
{
if (roster[i] == "Duty")
{
if (i > 1 && i < roster.Length - 2)
{
if (roster[i-2] == "Off" && roster[i-1] == "Off" && roster[i+1] == "Off" && roster[i+2] == "Off")
{
return true;
}
}
}
}