如何在 Java 中生成笛卡尔积? [英] How do I generate a Cartesian product in 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 objecta
, objectb
and objectc
ArrayListB
has objectd
, objecte
那么输出应该是 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
objecta
and objectd
,
Combination2
objecta
and objecte
,
Combination3
objectb
and objectd
,
Combination4
objectb
and objecte
,
Combination5
objectc
and objectd
,
Combination6
objectc
and objecte
,
有人可以帮我吗?
推荐答案
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屋!