How to use LINQ to find all combinations of n items from a set of numbers?

后端 未结 3 1080
时光说笑
时光说笑 2020-12-06 11:58

I\'m trying to write an algorithm to select all combinations of n values from a set of numbers.

For instance, given the set: 1, 2, 3, 7, 8, 9

Al

3条回答
  •  囚心锁ツ
    2020-12-06 12:13

    Usage:

    var results = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);
    

    Code:

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

提交回复
热议问题