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:
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; }
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!