In: Computer Science
JAVA: when input is type ArrayList<ArrayList<Integer>> how to use java to get this solution
[ [a,b,c] , [d,e], [f] ] ----> [ [a,d,f], [a,e,f], [b,d,f], [b,e,f], [c,d,f], [c,e,f]]
[ [a,b], [a,b,c]] ----->[[a,a],[a,b],[a,c], [b,a],[b,b],[b,c]
assuming abc are integer
Thanks in advance!
import java.util.ArrayList; import java.util.Arrays; public class IntCombinations { private static ArrayList<ArrayList<Integer>> mergeTwoLists(ArrayList<Integer> partList, ArrayList<ArrayList<Integer>> overallList) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); for (Integer x : partList) { for (ArrayList<Integer> y : overallList) { ArrayList<Integer> l2Copy = new ArrayList<>(y); l2Copy.add(0, x); result.add(l2Copy); } } return result; } public static ArrayList<ArrayList<Integer>> generateCombs(ArrayList<ArrayList<Integer>> lists) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); result.add(new ArrayList<>()); for(ArrayList<Integer> x: lists) { result = mergeTwoLists(x, result); } return result; } public static void main(String[] args) { ArrayList<Integer> x1 = new ArrayList<>(Arrays.asList(1, 2, 3)); ArrayList<Integer> x2 = new ArrayList<>(Arrays.asList(4, 5)); ArrayList<Integer> x3 = new ArrayList<>(Arrays.asList(6)); ArrayList<ArrayList<Integer>> result = generateCombs(new ArrayList<ArrayList<Integer>>(Arrays.asList(x1, x2, x3))); for(ArrayList<Integer> x: result) { System.out.println(x); } } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.