Iterative Cartesian Product in Java
Posted
by akappa
on Stack Overflow
See other posts from Stack Overflow
or by akappa
Published on 2009-11-12T02:56:16Z
Indexed on
2010/06/09
20:52 UTC
Read the original article
Hit count: 375
Hi,
I want to compute the cartesian product of an arbitrary number of nonempty sets in Java.
I've wrote that iterative code...
public static <T> List<Set<T>> cartesianProduct(List<Set<T>> list) {
List<Iterator<T>> iterators = new ArrayList<Iterator<T>>(list.size());
List<T> elements = new ArrayList<T>(list.size());
List<Set<T>> toRet = new ArrayList<Set<T>>();
for (int i = 0; i < list.size(); i++) {
iterators.add(list.get(i).iterator());
elements.add(iterators.get(i).next());
}
for (int j = 1; j >= 0;) {
toRet.add(Sets.newHashSet(elements));
for (j = iterators.size()-1; j >= 0 && !iterators.get(j).hasNext(); j--) {
iterators.set(j, list.get(j).iterator());
elements.set(j, iterators.get(j).next());
}
elements.set(Math.abs(j), iterators.get(Math.abs(j)).next());
}
return toRet;
}
...but I found it rather inelegant. Someone has a better, still iterative solution? A solution that uses some wonderful functional-like approach? Otherwise... suggestion about how to improve it? Errors?
Thanks :)
© Stack Overflow or respective owner