Words combinations without repetition

后端 未结 4 689
栀梦
栀梦 2020-12-03 18:58

I have 10 words. How can I get all possible combinations of 5 words (n=10, k=5). The order does not matter.

For example: \"A\",

4条回答
  •  执念已碎
    2020-12-03 19:12

    What you are trying to do is get all the permutations of a collection.

    • Unique permutations of list
    • permutations of k objects from a set of n algorithm

    Here is the code snippet:

    static void Main(string[] args)
    {
        var list = new List { "a", "b", "c", "d", "e" };
        var result = GetPermutations(list, 3);
        foreach (var perm in result)
        {
            foreach (var c in perm)
            {
                Console.Write(c + " ");
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }
    
    static IEnumerable> GetPermutations(IEnumerable items, int count)
    {
        int i = 0;
        foreach (var item in items)
        {
            if (count == 1)
                yield return new T[] { item };
            else
            {
                foreach (var result in GetPermutations(items.Skip(i + 1), count - 1))
                    yield return new T[] { item }.Concat(result);
            }
    
            ++i;
        }
    }
    

    Outputs:

    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 
    

提交回复
热议问题