First implementation of Combinations.

This commit is contained in:
Filip Strajnar 2024-05-07 23:34:55 +02:00
parent 579b10419e
commit c18c6533b2

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace AioNet.Linq
{
@ -10,7 +11,36 @@ namespace AioNet.Linq
int subsequenceLength
)
{
throw new NotImplementedException();
return source.Combinations<T>(subsequenceLength, Enumerable.Empty<T>());
}
private static IEnumerable<IEnumerable<T>> Combinations<T>(
this IEnumerable<T> source,
int subsequenceLength,
IEnumerable<T> build
)
{
if (build.Count() == subsequenceLength)
{
return new IEnumerable<T>[] { build };
}
if (!source.Any())
{
return Enumerable.Empty<IEnumerable<T>>();
}
IEnumerable<T> rest = source.Skip(1);
IEnumerable<IEnumerable<T>> combinationsSkipping = rest.Combinations(
subsequenceLength,
build
);
IEnumerable<IEnumerable<T>> combinationsTaking = rest.Combinations(
subsequenceLength,
build.Append(source.First())
);
return combinationsTaking.Concat(combinationsSkipping);
}
}
}