Home  >  Article  >  Java  >  How to Generate All Possible Unique Combinations from Multiple Lists in Java?

How to Generate All Possible Unique Combinations from Multiple Lists in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 19:57:02307browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn