Reputation: 2051
Im trying to write a function to display all combinations in a jagged array, where each combination contains one element from each sub-array. The jagged array can consist of any number of arrays and each array can have any number of elements. E.g. for the following array: a[0] = {1, 3, 5} a[1] = {2, 4} it should return: (1, 2) (1, 4) (3, 2) (3, 4) (5, 2) (5, 4)
I thought of doing it this way but immediately run into trouble. Logically it looks OK to get 1, 2 and 1, 4 but then next run I is set back to 0 (sorry not at devel machine to test now). Can anyone suggest a better solution please?
Here is my code
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])
Upvotes: 0
Views: 128
Reputation: 13196
Here's a general solution that works with any number of arrays (beware the exponential nature of the runtime of this algorithm):
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;
}
}
Upvotes: 0
Reputation: 1207
for (int i = 0; i < array1.length(); i++)
for (int j = 0; j < array2.length(); j++)
System.out.println("(" + array1[i] + "," array2[j] + ")");
Upvotes: 0
Reputation: 810
You don't need this:
if (j < array2.length())
i = 0;
else
i++;
i is incremented automatically in a for loop.
This should be fine:
for (int i = 0; i < array1.length(); i++)
for (int j = 0; j < array2.length(); j++)
System.out.println(array1[i] "," array2[j])
Upvotes: 1
Reputation: 115388
Your if
statement inside the loop breaks everything. You just need 2 nested loop to complete your task:
for (int i = 0; i < array1.length(); i++)
for (int j = 0; j < array2.length(); j++) {
System.out.println(array1[i] + "," + array2[j]);
}
}
Upvotes: 0
Reputation: 1967
How about this:
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]);
}
}
Upvotes: 0
Reputation: 6206
If I'm understanding your question correctly (which I might not be) I think all you need is just
for (int i = 0; i < array1.length(); i++){
for (int j = 0; j < array2.length(); j++){
System.out.println(array1[i] "," array2[j]);
}
}
to achieve the desired result
Upvotes: 0