Home > Java > javaTutorial > body text

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

Patricia Arquette
Release: 2024-10-26 19:57:02
Original
307 people have browsed it

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]
Copy after login

the function should yield 12 combinations:

[AW, AX, AY, AZ, BW, BX, BY, BZ, CW, CX, CY, CZ]
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!