Summary Code from an earlier article was solicited for inclusion into Mono and is now a part of the Mono.Rocks extension methods library.
An earlier article from this blog described how to use sliding windows to obtain contiguous subsequences, and provided a sample implementation in the form of an extension method. The excellent Jon Pryor of Novell wrote in to let me know he was planning to include it. With a few modifications and some unit tests, the finished product is now part of the "Mono.Rocks subproject", which provides extension methods to augment base classes.
As committed, the code looks like this:
public static IEnumerable<IEnumerable<TSource>>
ContiguousSubsequences<TSource>(this IEnumerable<TSource> self, int windowSize)
{
Check.Self (self);
if (windowSize < 1)
throw new ArgumentOutOfRangeException("windowSize", "must be >= 1");
return CreateContiguousSubsequencesIterator (self, windowSize);
}
private static IEnumerable<IEnumerable<T>>
CreateContiguousSubsequencesIterator<T>(this IEnumerable<T> input, int windowSize)
{
int index = 0;
var window = new List<T>(windowSize);
window.AddRange (new T[windowSize]);
foreach (var item in input) {
bool initializing = index < windowSize;
if (!initializing) {
window = window.Skip (1).ToList ();
window.Add (default (T));
}
int itemIndex = initializing ? index : windowSize - 1;
window [itemIndex] = item;
index++;
bool initialized = index >= windowSize;
if (initialized)
yield return new List<T>(window);
}
}


