2013-06-18 51 views
0

我试图编写一个函数来显示锯齿阵列中的所有组合,其中每个组合都包含来自每个子阵列的一个元素。锯齿状数组可以包含任意数量的数组,每个数组可以包含任意数量的元素。例如。以下数组: 一个[0] = {1,3,5} 一个[1] = {2,4} 它应该返回: (1,2) (1,4) (3, 2) (3,4) (5,2) (5,4)在数组中打印数字

我觉得做这种方式,但马上遇到麻烦。从逻辑上看它可以获得1,2和1,4,但是接下来的运行我被设置回0(抱歉不在开发机器现在测试)。 任何人都可以提出更好的解决方案吗?

这里是我的代码

for (int i = 0; i < array1.length(); i++) 
    for (int j = 0; j < array2.length(); j++) 

     if (j < array2.length()) 
      i = 0; 
     else 
      i++; 

     System.out.println(array1[i] "," array2[j]) 
+0

什么是否再次需要? –

+0

我没有看到你有什么后面的原因,没有它应该打印所有的数组组合。 – Zoop

+0

如果你不想这样做,那么使用这个[库](http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/index.html) – DarthCoder

回答

1

你不需要这样的:

if (j < array2.length()) 
      i = 0; 
     else 
      i++; 

我是在自动递增循环。

这应该是罚款:

for (int i = 0; i < array1.length(); i++) 
    for (int j = 0; j < array2.length(); j++) 
     System.out.println(array1[i] "," array2[j]) 
0

如果我正确理解你的问题(我可能不是),我认为你需要的只是

for (int i = 0; i < array1.length(); i++){ 
    for (int j = 0; j < array2.length(); j++){ 
    System.out.println(array1[i] "," array2[j]); 
    } 
} 

,以达到预期的效果

0

这个怎么样:

int a [] = {1,2,3}; int b [] = {1,2};

for (int i = 0; i < b.length; i++) { 
    for (int j = 0; j < a.length; j++) { 
     System.out.println(a[i]+","+a[j]); 

    } 

} 
0

您在环路内的if声明会破坏所有内容。你只需要2个嵌套循环来完成你的任务:

for (int i = 0; i < array1.length(); i++) 
    for (int j = 0; j < array2.length(); j++) { 
     System.out.println(array1[i] + "," + array2[j]); 
    } 
} 
0
for (int i = 0; i < array1.length(); i++) 
    for (int j = 0; j < array2.length(); j++) 
     System.out.println("(" + array1[i] + "," array2[j] + ")"); 
0

这里是与任意数量的阵列的工作有一个大致的解决方案(注意这个算法的运行时间的指数性质):

int[][] arrays = new int[][] 
{ 
    {1, 2, 3, 4, 5, 6}, 
    {1, 2, 3, 4, 5, 6}, 
    {1, 2, 3, 4, 5, 6} 
}; // let's print all fair rolls of a 3d6 

if (arrays.length == 0) return; // this is why we can't have nice things 

int[] currentPos = new int[arrays.length]; 

while(currentPos[arrays.length - 1] != arrays[arrays.length - 1].length) 
{ 
    // print the current value 
    System.out.print(arrays[0][currentPos[0]]); 
    for (int i = 1; i < arrays.length; ++i) 
     System.out.print(", " + arrays[i][currentPos[i]]); 
    System.out.println(); 

    // increment the "counter" 
    ++currentPos[0]; 
    for (int i = 1; i < arrays.length; ++i) 
    { 
     if (currentPos[i - 1] == arrays[i - 1].length) 
     { 
      currentPos[i - 1] = 0; 
      ++currentPos[i]; 
     } 
     else break; 
    } 
}