10. Given the definition of a 2D array such as the following, String[][] data =
ID: 3737127 • Letter: 1
Question
10. 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
Explanation / Answer
import java.util.ArrayList;
public class StringManupulation {
public String getAllCombinations(ArrayList<ArrayList<String>> data) {
//Base condition - when the final merged list is obtained - create the string and return
if(data.size() <= 1) {
String ans = "";
for(String s : data.get(0)) {
ans += s + " ";
}
return ans;
}
//merge - dynamically merge arrays - eg: {{"A", "B"}, {"1", "2"}, {"XX","YY","ZZ"}}
// -> {{"A 1", "A 2", "B 1", "B 2"}, {"XX","YY","ZZ"}}
// -> {{"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"}
ArrayList<String>>
ArrayList<String> two = data.remove(0);
ArrayList<String> newList = new ArrayList<>();
for(String s1: one) {
for(String s2: two) {
newList.add(s1+ " " + s2);
}
}
data.add(0, newList);
return getAllCombinations(data);
}
public static void main(String []args)
{
StringManupulation combinations = new StringManupulation();
String[][] data = {{"A", "B"}, {"1", "2"}, {"XX","YY","ZZ"}};
String finalString = "";
if(data.length == 1)
{
for (int i=0;i<data[0].length;i++)
{
System.out.print(data[0][i] + " ");
}
System.out.println();
}
else
{
ArrayList<ArrayList<String>> dataList = new ArrayList<>();
//Create an ArrayList of ArrayList to get dynamic feature
for(String[] eles: data) {
ArrayList<String> temp = new ArrayList<>();
for (String ele: eles) {
temp.add(ele);
}
dataList.add(temp);
}
int sizeOf2dArray = data.length;
finalString = combinations.getAllCombinations(dataList);
System.out.println(finalString);
}
}
}
For the above question following is the 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
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.