组合中必须包含无重复的组合

时间:2018-11-16 17:39:37

标签: c# combinations non-repetitive

我有2个int列表,我需要所有可能的组合的列表,且不重复5个数字。但是它还需要包含另一个列表中的所有int

示例:

var takeFrom = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var mustInclude = new List<int> { 1, 3, 5 };

我一直在使用KwCombinatorics,但要花一些时间才能完成。几乎80%的结果都是无用的,因为它不包含int列表中的mustInclude

输出示例:

var result = new List<int> 
{
     { 1, 3, 5, 9, 10 },
     { 1, 3, 5, 8, 7 },
     { 1, 3, 5, 6, 9 },
}

它不必按此顺序排列,只要它不包含重复。

2 个答案:

答案 0 :(得分:2)

借用this Question GetAllCombos ,并使用@juharr的想法,相信以下代码会为您提供所需的结果。

List<int> takeFrom = new List<int> { 2, 4, 6, 7, 8, 9, 10 };
    List<int> mustInclude = new List<int> { 1, 3, 5 };

    protected void Page_Load(object sender, EventArgs e)
    {
        List<List<int>> FinalList = new List<List<int>>();

        FinalList = GetAllCombos(takeFrom);
        FinalList = AddListToEachList(FinalList, mustInclude);

        gvCombos.DataSource = FinalList;
        gvCombos.DataBind();
    }

    // Recursive
    private static List<List<T>> GetAllCombos<T>(List<T> list)
    {
        List<List<T>> result = new List<List<T>>();
        // head
        result.Add(new List<T>());
        result.Last().Add(list[0]);
        if (list.Count == 1)
            return result;
        // tail
        List<List<T>> tailCombos = GetAllCombos(list.Skip(1).ToList());
        tailCombos.ForEach(combo =>
        {
            result.Add(new List<T>(combo));
            combo.Add(list[0]);
            result.Add(new List<T>(combo));
        });
        return result;
    }

    private static List<List<int>> AddListToEachList(List<List<int>> listOfLists, List<int> mustInclude)
    {
        List<List<int>> newListOfLists = new List<List<int>>();

        //Go through each List
        foreach (List<int> l in listOfLists)
        {
            List<int> newList = l.ToList();

            //Add each item that should be in all lists
            foreach(int i in mustInclude)
                newList.Add(i);

            newListOfLists.Add(newList);
        }

        return newListOfLists;
    }

    protected void gvCombos_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            List<int> drv = (List<int>)e.Row.DataItem;
            Label lblCombo = (Label)e.Row.FindControl("lblCombo");

            foreach (int i in drv)
                lblCombo.Text += string.Format($"{i} "); 
        }
    }

GetAllCombos 为您提供了所有组合,而没有所有列表所需的数字,然后第二个 AddListToEachList 方法会将所需的数字添加到每个列表中。

答案 1 :(得分:1)

正如评论中已经建议的那样,您可以从列表中删除三个必需的数字,并生成两个而不是五个的组合。

类似这样的东西:

takeFrom = takeFrom.Except(mustInclude).ToList();
listOfPairs = KwCombinatorics(takeFrom, 2);
result = listOfPairs.Select(pair => mustInclude.Concat(pair).ToList()).ToList();
相关问题