如何在 Java 中生成笛卡尔积? [英] How do I generate a Cartesian product in Java?

查看:30
本文介绍了如何在 Java 中生成笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多 ArrayList,每个 ArrayList 都有对象,每个对象都可以有不同的长度.我需要像下面的例子一样生成排列:

I have a number of ArrayList with each ArrayList having objects and each one can have different length. I need to generate permutation like in the below example:

假设我有 2 个 ArrayList:

ArrayList A 有对象 a、对象 b 和对象 c
ArrayList B 有对象 d,对象 e

ArrayList A has object a, object b and object c
ArrayList B has object d, object e

那么输出应该是 6 个新的 ArrayList 与这些组合:

Then the output should be 6 new ArrayList with these combinations:

组合1对象a和对象d,
组合2对象a和对象e,
组合3对象b和对象d,
组合4对象b和对象e,
组合5对象c和对象d,
组合6对象c和对象e,

Combination 1 object a and object d,
Combination 2 object a and object e,
Combination 3 object b and object d,
Combination 4 object b and object e,
Combination 5 object c and object d,
Combination 6 object c and object e,

有人可以帮我吗?

推荐答案

Guava 19+

Lists.cartesianProduct(List...)

例如:

List<Object> list1 = Arrays.asList("a", "b", "c");
List<Object> list2 = Arrays.asList("d", "e");
System.out.println(Lists.cartesianProduct(list1, list2));

输出:

[[a, d], [a, e], [b, d], [b, e], [c, d], [c, e]]

这篇关于如何在 Java 中生成笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆