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

查看:168
本文介绍了如何用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

suppose i have 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 this 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,

任何人都可以帮助我吗?

Can anyone help me?

推荐答案

Guava 19 +



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天全站免登陆