Certain not quite as compact, but the following also handles the situation when the lead items in the array are not zero. And with the addition of the "target" parameter count can be found between any integer value.
private static IEnumerable<int> CountSequenceInArray(IEnumerable<int> seq, int target)
{
var foundLastZero = false;
int startCount = 0;
foreach(var item in seq)
{
var isZero = item.Equals(target);
if(!isZero && foundLastZero)
{
startCount++;
continue;
}
else if(isZero && startCount > 0)
{
yield return startCount;
startCount = 0;
}
foundLastZero = isZero;
}
}
With the following test set:
static void Main(string[] args)
{
Console.WriteLine(“—— Start ——”);
int[] a0 = {0,0,0,0,1};
int[] a1 = {0,0,1,2,3,4,0,0,0};
int[] a2 = {0,1,2,3,4,0,0,0,1,2,3,0,0,9,0};
int[] a3 = {1,2,3,4,0,0,0,1,2,3,0,0,9};
int[] a4 = {1,2,3,4,0,1,2,0,1,2,3,0,1,0,1,2,3,0,0,9,0,8};
var listArrays = new List<int[]>();
listArrays.Add(a0);
listArrays.Add(a1);
listArrays.Add(a2);
listArrays.Add(a3);
listArrays.Add(a4);
foreach(var arr in listArrays)
{
Console.WriteLine();
CountSequenceInArray(arr, 0).ToList().ForEach(x => Console.Write($"Zeros {x} | "));
}
}
Results:
(a0 yields no results)
Zeros 4 |
Zeros 4 | Zeros 3 | Zeros 1 |
Zeros 3 |
Zeros 2 | Zeros 3 | Zeros 1 | Zeros 3 | Zeros 1 |
dotnet var array1 = new int[] {0, 0, 1, 4, 3, 1, 0, 0, 0}