If I have a sequence as follows (let's say it's an IEnumerable<T>
):
[A, B, C, D, E]
Then what's the cleanest way to compute all possible (continuous and non-continuous) subsequences of a given length? Ordering of the results in the result set isn't important, but it shouldn't include duplicates.
e.g. If I want to compute all possible subsequences of length 3 the result set would be:
[A, B, C]
[A, B, D]
[A, B, E]
[A, C, D]
[A, C, E]
[A, D, E]
[B, C, D]
[B, C, E]
[B, D, E]
[C, D, E]
For the record, the accepted answer below gave me a good starting point, and here's the code I've gone with that is updated to use some of the new .NET 3.5 extension methods:
public static IEnumerable<IEnumerable<T>> Subsequences<T>(
this IEnumerable<T> source,
int count)
{
if (count == 0)
{
yield return Enumerable.Empty<T>();
}
else
{
var skip = 1;
foreach (var first in source)
{
foreach (var rest in source.Skip(skip).Subsequences(count - 1))
{
yield return Enumerable.Repeat(first, 1).Concat(rest);
}
skip++;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…