Home >Java >javaTutorial >How to Generate All Possible Unique Combinations from Multiple Lists in Java?
Multiple List Combination Generator in Java
Question:
Given a variable number of lists of arbitrary length, generate a single list containing all possible unique combinations of elements across all input lists. For instance, given lists:
X: [A, B, C] Y: [W, X, Y, Z]
the function should yield 12 combinations:
[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
Answer:
This problem calls for a recursive approach:
<code class="java">void generatePermutations(List<List<Character>> lists, List<String> result, int depth, String current) { if (depth == lists.size()) { result.add(current); return; } for (int i = 0; i < lists.get(depth).size(); i++) { generatePermutations(lists, result, depth + 1, current + lists.get(depth).get(i)); } }</code>
To use this function:
<code class="java">List<List<Character>> lists = new ArrayList<>(); lists.add(Arrays.asList('A', 'B', 'C')); lists.add(Arrays.asList('W', 'X', 'Y', 'Z')); List<String> result = new ArrayList<>(); generatePermutations(lists, result, 0, "");</code>
The above is the detailed content of How to Generate All Possible Unique Combinations from Multiple Lists in Java?. For more information, please follow other related articles on the PHP Chinese website!