I'm trying to practice recursion, but for the life of me I can't figure out how to do this. Let's say I have 3 or more array lists inside of an array list, and I'd like to print out all possible combinations using recursion. How can I do that?
This is what I have so far
public static void main(String[] args) { ArrayList<ArrayList<String>> combList = new ArrayList<ArrayList<String>>(); ArrayList<String> fruitList = new ArrayList<String>(); ArrayList<String> lNameList = new ArrayList<String>(); ArrayList<String> locationList = new ArrayList<String>(); fruitList.add("Apple"); fruitList.add("Orange"); fruitList.add("Grape"); combList.add(fruitList); colorList.add("Red"); colorList.add("Green"); colorList.add("Blue"); combList.add(colorList); numberList.add("One"); numberList.add("Two"); numberList.add("Three"); combList.add(numberList); combinations(combList, 0, 0, ""); } public static void combinations(ArrayList<ArrayList<String>> combList, int listIndex, int itemIndex, String result) { // Am I at the bottom of the y-axis? if(listIndex < combList.size()) { //Am I at the bottom of the x-axis? if(itemIndex < combList.size()) { ArrayList<String> curList = combList.get(listIndex); StringBuilder sb = new StringBuilder(); sb.append(result).append(curList.get(itemIndex)).append(" "); combinations(combList, listIndex + 1, itemIndex, sb.toString()); combinations(combList, listIndex, itemIndex + 1, result); } return; } System.out.println(result); return; } I'm trying to get it to printout
Apple Red One Apple Red Two Apple Red Three Apple Green One Apple Green Two Apple Green Three Apple Blue One Apple Blue Two Apple Blue Three Orange Red One Orange Red Two Orange Red Three Orange Green One . . . Grape Blue Three
combList. Then at each level coming back up you take the result of the recursive call, and for every element from your result you append each element from the list you removed at that level. So at the bottom of your recursion you return['One', 'Two', 'Three']. Next level up you return['Red One', 'Red Two', 'Red Three' 'Green One', 'Green Two', 'Green Three', 'Blue One', ...]. Next level up you add the fruits. This will work for any number of lists.