vendredi 8 mai 2015

How to understand the following C# linq code of implementing the algorithm to return all combinations of k elements from n

Anyone can elaborate some details on this code or even give a non-Linq version of this algorithm:

public static IEnumerable<IEnumerable<T>> Combinations<T>
    (this IEnumerable<T> elements, int k)
{
   return k == 0 ? new[] { new T[0] }
                 : elements.SelectMany(
                       (e, i) =>
                         elements
                         .Skip(i + 1)
                         .Combinations(k - 1)
                         .Select(c => (new[] {e}).Concat(c)));
}

Aucun commentaire:

Enregistrer un commentaire