Home > Java > javaTutorial > How to Calculate the Cartesian Product of Multiple Sets in Java?

How to Calculate the Cartesian Product of Multiple Sets in Java?

Mary-Kate Olsen
Release: 2024-12-07 14:26:11
Original
865 people have browsed it

How to Calculate the Cartesian Product of Multiple Sets in Java?

Cartesian Product of Multiple Sets in Java

Determining the Cartesian product of two or more sets is a common task in programming. Here's how to perform this operation using Java libraries.

Recursive Approach

For an arbitrary number of sets, a recursive approach can be employed. The cartesianProduct method accepts an array of sets as arguments. It checks if the number of sets is valid and proceeds with the following steps:

  1. Base Case: If the number of sets is one, an empty set is returned.
  2. Recursive Step: For each element in the current set, it recursively calls itself to obtain Cartesian products of the remaining sets.
  3. Adds the current element to each product from the recursive call and adds it to the result set.

Sample Code:

public static Set<Set<Object>> cartesianProduct(Set<?>... sets) {
    if (sets.length < 2)
        throw new IllegalArgumentException("Can't have a product of fewer than two sets (got " + sets.length + ")");

    return _cartesianProduct(0, sets);
}

private static Set<Set<Object>> _cartesianProduct(int index, Set<?>... sets) {
    Set<Set<Object>> ret = new HashSet<>();
    if (index == sets.length) {
        ret.add(new HashSet<>());
    } else {
        for (Object obj : sets[index]) {
            for (Set<Object> set : _cartesianProduct(index + 1, sets)) {
                set.add(obj);
                ret.add(set);
            }
        }
    }
    return ret;
}
Copy after login

Note: This approach guarantees a Cartesian product for any number of sets but cannot preserve generic type information due to Java's limitations.

The above is the detailed content of How to Calculate the Cartesian Product of Multiple Sets 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