Given the definition of a 2D array such as the following,
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 (although it does not have to be in this order) is
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
example, the following data
String[][] data = {
{"A"},
{"1"},
{"2"},
{"XX","YY"}
};
should output:
A 1 2 YY
A 1 2 YY
PROGRAM CODE:
public class Test Demo
{
// Recursive method to print all combinations of the 2D array
private static void printCombinations(String[][] data, String[] currentCombination, int level)
{
// If the level reaches the number of rows in the 2D array, we have a complete combination
if (level == data.length)
{
for (String value : currentCombination)
{
System.out.print(value + " ");
}
System.out.println();
return;
}
// Loop through the elements of the current row and recursively call for the next level
for (String item : data[level]) {
currentCombination[level] = item;
printCombinations(data, currentCombination, level + 1);
}
}
public static void main(String[] args)
{
String[][] data = {
{"A", "B"},
{"1", "2"},
{"XX", "YY", "ZZ"}
};
// Calculate the total number of combinations and initialize the array
//to store the current combination
int totalCombinations = 1;
for (String[] row : data) {
totalCombinations *= row.length;
}
String[] currentCombination = new String[data.length];
// Print all combinations
printCombinations(data, currentCombination, 0);
}
}
OUTPUT:
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