2D数组的所有可能组合 - c#

            
        

我想从2D [m x n]数组中生成所有可能的组合,但每个数组的第一个元素除外。该元素将代表表示其余元素的“类型”。例如,如果我有一个数组

shirts[][] = 
{
  {"colour", "red", "blue", "green", "yellow"},
  {"cloth", "cotton", "poly", "silk"},
  {"type", "full", "half"}
};

期望的输出应该是衬衫所有可能性的组合。对于以上示例,

colour red
colour blue
...
cloth silk
type full
type half
colour red cloth cotton
colour red cloth poly
...
colour yellow type half
cloth cotton type full
...
cloth silk type half
colour red cloth cotton type full
...
colour yellow cloth silk type half

我尝试过这样的事情(也得到了其他Stack Overflow Question的帮助)

String shirts[][] = 
{
  {"colour", "red", "blue", "green", "yellow"},
  {"cloth", "cotton", "poly", "silk"},
  {"type", "full", "half"}
};

majorCombinations = new int[possibilities][shirts.length];

int currentCombination;
int offset = 1;

for (int i=0; i < shirts.length; i++)
{
    currentCombination = 0;
    while (currentCombination < possibilities)
    {
        for (int j=0; j < shirts[i].length; j++)
        {
            for (int k=0; k < offset; k++)
            {
                if (currentCombination < possibilities)
                {
                    majorCombinations[currentCombination][i] = shirts[i][j];
                    currentCombination++;
                }
            }
        }
    }
    offset *= shirts[i].length;
}

但它只给出所有n个组合的值,即

colour cloth type
colour cloth full
...
yellow silk half

它没有考虑较小的组合,甚至都不是通用的,即[m x n]数组(n不需要固定)。非常感谢VBA的帮助。我对C,Java和C#感到满意。
提前致谢 :)

编辑:

这与question asked here不同。这不是笛卡尔积,其中一个元素是从每个相关数组中选取的。我需要的输出没有设置此限制;因此,此方案中的组合数>链接问题中的组合数。
同样,第一列是内容的描述符,并且必须伴随内容。

参考方案

Link to Original Answer

对于两个数组,应执行两个嵌套循环:

for (int i = 0 ; i != c[0].length ; i++) {
    for (int j = 0 ; j != c[1].length ; j++) {
        System.out.writeln(""+c[0][i]+c[1][j]);
    }
}

对于更多的嵌套,您将需要一个递归的或等效的基于堆栈的解决方案。

void combos(int pos, char[][] c, String soFar) {
    if (pos == c.length) {
         System.out.writeln(soFar);
         return;
    }
    for (int i = 0 ; i != c[pos].length ; i++) {
        combos(pos+1, c, soFar + c[pos][i]);
    }
}

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

改造正在返回一个空的响应主体 - java

我正在尝试使用Retrofit和Gson解析一些JSON。但是,我得到的响应机构是空的。当我尝试从对象中打印信息时,出现NullPointerException。我确保URL正确,并且我也确保POJO也正确。我正在使用jsonschema2pojo来帮助创建POJO类。这是我要解析的JSON{ "?xml": { "@versi…

每个文件合并后添加换行 - python

我有很多类似以下内容的JSON文件:例如。1.json{"name": "one", "description": "testDescription...", "comment": ""} test.json{"name"…

您如何在列表内部调用一个字符串位置? - python

我一直在做迷宫游戏。我首先决定制作一个迷你教程。游戏开发才刚刚开始,现在我正在尝试使其向上发展。我正在尝试更改PlayerAre变量,但是它不起作用。我试过放在列表内和列表外。maze = ["o","*","*","*","*","*",…

Mongo汇总 - javascript

我的收藏中有以下文件{ "_id": ObjectId("54490b8104f7142f22ecc97f"), "title": "Sample1", "slug": "samplenews", "cat": …