From c18c6533b28a74ec5ab472096046908852d96ba5 Mon Sep 17 00:00:00 2001 From: Filip Strajnar Date: Tue, 7 May 2024 23:34:55 +0200 Subject: [PATCH] First implementation of Combinations. --- AioNet.Linq/ExtendedLinq.cs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/AioNet.Linq/ExtendedLinq.cs b/AioNet.Linq/ExtendedLinq.cs index 0145f42..7a0f089 100644 --- a/AioNet.Linq/ExtendedLinq.cs +++ b/AioNet.Linq/ExtendedLinq.cs @@ -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(subsequenceLength, Enumerable.Empty()); + } + + private static IEnumerable> Combinations( + this IEnumerable source, + int subsequenceLength, + IEnumerable build + ) + { + if (build.Count() == subsequenceLength) + { + return new IEnumerable[] { build }; + } + + if (!source.Any()) + { + return Enumerable.Empty>(); + } + + IEnumerable rest = source.Skip(1); + + IEnumerable> combinationsSkipping = rest.Combinations( + subsequenceLength, + build + ); + IEnumerable> combinationsTaking = rest.Combinations( + subsequenceLength, + build.Append(source.First()) + ); + return combinationsTaking.Concat(combinationsSkipping); } } }