一个二维数组的所有可能的组合 [英] All possible combinations of a 2D array

查看:120
本文介绍了一个二维数组的所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

欲生成从2D [m×n个]阵列的所有可能的组合,除了每个阵列的第一个元素。该元素将站在为'型',表示其余的元素。举例来说,如果我有一个数组

I want to generate all possible combinations from a 2D [m x n] array except for the first element of each array. That element will stand for the 'type' signifying the rest elements. For example, if I've an array

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



所需的输出应该是衬衫的一切准备结合。对于上面的例子中,

The desired output should be combination of all the possibilities of shirt. For the above example,

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

我想这样的事情(也帮助了其他堆栈溢出的问题

I tried something like this (also took help from other 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个组合只有IE

but it gives values of ALL n combinations only i.e.

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

它没有考虑到更小的组合,这是不连为[m×n个]数组通用即(正不需要固定)。在VBA中帮助将高度赞赏。我很舒服与C,Java和C#为好。提前
感谢:)

It doesn't take into account smaller combinations and it ain't even generic i.e. for an [m x n] array (n need not be fixed). A help in VBA would be highly appreciated. I'm comfortable with C, Java and C# as well. Thanks in advance :)

推荐答案

链接到原来的答案

有关两个数组的嵌套循环应该做的:

For two arrays two nested loops should do:

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]);
    }
}

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

For more nesting you would need a recursive or an equivalent stack-based solution.

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]);
    }
}

这篇关于一个二维数组的所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆