Reputation: 63
I'm stuck on the following problem using Java. I will include my code at the bottom of this post. I get most of the combinations however I can't figure out a way to get my column variable to be 0 for the remainder of my recursive calls which would help me in getting all combinations. The solution must work for two dimensional arrays of all sizes. Preferably I would like the solution to be entirely recursion - no loops. Thank you for any insight you may provide.
Given the definition of a 2D array such as follows:
String[][] data = {
{"A", "B"},
{"1", "2"},
{"XX","YY","ZZ"}
};
Write a recursive program that outputs all combinations of each subarray in order. In the previous example, the desired output might look like the following:
A 1 XX
A 1 YY
A 1 ZZ
A 2 XX
A 2 YY
A 2 ZZ
B 1 XX
B 1 YY
B 1 ZZ
B 2 XX
B 2 YY
B 2 ZZ
Your program should work with arbitrarily sized arrays in either dimension. For instance, consider the following input array:
String[][] data = {
{"A"},
{"1"},
{"2"},
{"XX","YY"}
};
Should output:
A 1 2 YY
A 1 2 YY
My solution so far:
private String[][] data = {
{"A", "B"},
{"1", "2"},
{"XX","YY","ZZ"}
};
public void combinations() {
helperMethod("",0, 0);
}
private void helperMethod(String oldCombination, int row, int col) {
String newCombination = oldCombination + data[row][col];
if (row == data.length - 1) {
System.out.println(newCombination);
}
if (row < data.length - 1) {
helperMethod(newCombination, row + 1, col);
}
if (col < data[row].length - 1) {
helperMethod(oldCombination, row, col + 1);
}
}
Upvotes: 3
Views: 2426
Reputation: 3863
When you move to the next row, you have to reset the column back to zero:
if (row < data.length - 1) {
helperMethod(newCombination, row + 1, 0); // 0 instead of col
}
With that small change it seems to work correctly at least with the test cases you provided.
Upvotes: 2