Home >Java >javaTutorial >How Can I Efficiently Compute the Cartesian Product of Multiple Sets in Java?
Efficient Cartesian Product Computation for Multiple Sets
Obtaining the Cartesian product of multiple sets can be a useful operation in programming. It involves generating a new set containing all possible combinations of elements from the input sets. In Java, there are a few libraries that can facilitate this task.
Recursive Solution for Arbitrary Number of Sets
However, if the number of sets varies dynamically, a recursive solution can be implemented:
public static Set<Set<Object>> cartesianProduct(Set<?>... sets) { if (sets.length < 2) throw new IllegalArgumentException("Product requires at least 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; }
This recursive function takes an array of sets as input and iteratively combines elements from each set to form the Cartesian product. Note that this solution cannot preserve generic type information due to Java's limitations.
The above is the detailed content of How Can I Efficiently Compute the Cartesian Product of Multiple Sets in Java?. For more information, please follow other related articles on the PHP Chinese website!