aka*_*ppa 18 java algorithm cartesian-product
我想用Java 计算任意数量的非空集的笛卡尔积.
我写过那个迭代代码......
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;
}
Run Code Online (Sandbox Code Playgroud)
......但我发现它相当不优雅.有人有更好的,仍然是迭代的解决方案吗?使用一些奇妙的功能性方法的解决方案?否则......关于如何改进它的建议?错误?
Kev*_*ion 23
我写了一个解决方案,不要求你在内存中填满大量的集合.不幸的是,所需的代码长达数百行.您可能要等到它出现在Guava项目(http://guava-libraries.googlecode.com)中,我希望将在今年年底之前.抱歉.:(
请注意,如果您生成的笛卡儿产品的数量是编译时已知的固定数量,则可能不需要这样的实用程序 - 您可以使用该数量的嵌套for循环.
编辑:代码现在发布.
我想你会很开心的.它只会在您要求时创建单个列表; 没有用它们的所有MxNxPxQ填充内存.
如果你想检查来源,请点击第727行.
请享用!
使用 Google Guava 19 和 Java 8 非常简单:
假设您拥有要关联的所有数组的列表...
public static void main(String[] args) {
List<String[]> elements = Arrays.asList(
new String[]{"John", "Mary"},
new String[]{"Eats", "Works", "Plays"},
new String[]{"Food", "Computer", "Guitar"}
);
// Create a list of immutableLists of strings
List<ImmutableList<String>> immutableElements = makeListofImmutable(elements);
// Use Guava's Lists.cartesianProduct, since Guava 19
List<List<String>> cartesianProduct = Lists.cartesianProduct(immutableElements);
System.out.println(cartesianProduct);
}
Run Code Online (Sandbox Code Playgroud)
制作不可变列表的方法如下:
/**
* @param values the list of all profiles provided by the client in matrix.json
* @return the list of ImmutableList to compute the Cartesian product of values
*/
private static List<ImmutableList<String>> makeListofImmutable(List<String[]> values) {
List<ImmutableList<String>> converted = new LinkedList<>();
values.forEach(array -> {
converted.add(ImmutableList.copyOf(array));
});
return converted;
}
Run Code Online (Sandbox Code Playgroud)
输出如下:
[
[John, Eats, Food], [John, Eats, Computer], [John, Eats, Guitar],
[John, Works, Food], [John, Works, Computer], [John, Works, Guitar],
[John, Plays, Food], [John, Plays, Computer], [John, Plays, Guitar],
[Mary, Eats, Food], [Mary, Eats, Computer], [Mary, Eats, Guitar],
[Mary, Works, Food], [Mary, Works, Computer], [Mary, Works, Guitar],
[Mary, Plays, Food], [Mary, Plays, Computer], [Mary, Plays, Guitar]
]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11382 次 |
最近记录: |