迭代计算任意数量的集合的笛卡尔积 [英] Iteratively compute the Cartesian product of an arbitrary number of sets
问题描述
我想计算Java中任意数量的 nonempty 集的笛卡尔积.
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?
推荐答案
我写了一个不需要您在内存中填满大集合的解决方案.不幸的是,所需的代码长达数百行.您可能需要等到它出现在Guava项目中( https://github.com/google/guava),我希望到今年年底.对不起.:(
I've written a solution that doesn't require you to fill up a large collection in memory. Unfortunately, the code required is hundreds of lines long. You may have to wait until it appears in the Guava project (https://github.com/google/guava), which I hope will be by the end of the year. Sorry. :(
请注意,如果笛卡尔乘积的集合数是编译时已知的固定数,则可能不需要这样的实用程序-您可以仅使用该数目的嵌套for循环.
Note that you may not need such a utility if the number of sets you're cartesian-producting is a fixed number known at compile time -- you could just use that number of nested for loops.
编辑:该代码现已发布.
我认为您会对此感到非常满意.它仅根据您的要求创建单个列表.不会用它们中的所有MxNxPxQ填满内存.
I think you'll be very happy with it. It only creates the individual lists as you ask for them; doesn't fill up memory with all MxNxPxQ of them.
如果您要检查源,则为此处.
If you want to inspect the source, it's here.
享受!
这篇关于迭代计算任意数量的集合的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!