Words combinations without repetition

后端 未结 4 692
栀梦
栀梦 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:17

    What about a more functional solution

    var list = new List { "a", "b", "c", "d", "e" };
    GetAllCombinations(list).OrderBy(_ => _).ToList().ForEach(Console.WriteLine);
    
    
    static IEnumerable GetAllCombinations(IEnumerable list)
    {
        return list.SelectMany(mainItem => list.Where(otherItem => !otherItem.Equals(mainItem))
                                  .Select(otherItem => mainItem + otherItem));
    }
    

    Ouput:

    ab
    ac
    ad
    ae
    ba
    bc
    bd
    be
    ca
    cb
    cd
    ce
    da
    db
    dc
    de
    ea
    eb
    ec
    ed
    

提交回复
热议问题