首页 > 解决方案 > c# 显示可能的组合

问题描述

我有 20 个花盆,用于创建 2 个花盆分组的时间表。我需要找到可以创建的所有可能的时间表。

// create range of pots
 IEnumerable<int> pots = Enumerable.Range(1, 20);

获取所有可能的 2 个锅组:

    public DataTable CreateCombinations(IEnumerable<int> pots)
    {

        DataTable testTable = new DataTable();
        testTable.Columns.Add("Pot1");
        testTable.Columns.Add("Pot2");
        for (int i = 0; i < pots.Count(); i++)
        {
            for (int j = i + 1; j < pots.Count(); j++)
            {
                var row = testTable.NewRow();
                row["Pot1"] = pots.ElementAt(i);
                row["Pot2"] = pots.ElementAt(j);
                testTable.Rows.Add(row);
            }
        }

        return testTable;
    }

可以从 1,n 组合创建的所有可能计划的列表:

public DataTable CreatePossibleSchedules(DataTable dt)
        {
            DataTable testTable = new DataTable();
            testTable.Columns.Add("Pot1");
            testTable.Columns.Add("Pot2");
            testTable.Columns.Add("Schedule");
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                if(dt.Rows[i]["Pot1"].ToString() == "1")
                {
                    for (var x = i; x < dt.Rows.Count; x++)
                    {
                        string pot1 = dt.Rows[x]["Pot1"].ToString();
                        string pot2 = dt.Rows[x]["Pot2"].ToString();
                        string schedule = (i + 1).ToString();
                        bool exists = testTable.AsEnumerable().Any(row => 
(pot1 == row.Field<string>("Pot1") || pot1 == row.Field<string>("Pot2") || 
pot2 == row.Field<string>("Pot1") || pot2 == row.Field<string>("Pot2")) && 
schedule == row.Field<string>("Schedule"));
                        if (!exists)
                        {
                            var row = testTable.NewRow();
                            row["Pot1"] = dt.Rows[x]["Pot1"];
                            row["Pot2"] = dt.Rows[x]["Pot2"];
                            row["Schedule"] = i + 1;
                            testTable.Rows.Add(row);
                        }
                    }
                }                
            }

            return testTable;
        }

这给了我 1,2 到 1,20 的可能时间表:
时间表 1:
1,2
3,4
...
19,20
到时间表 20:
1、20
2、3
18、19

我不知道该怎么做就是重新开始获取其余可能的时间表:
时间表 21:
1、2
3、5
4、6

希望这是有道理的,不确定我是否已经很好地解释了这个问题。

标签: c#

解决方案


推荐阅读