java 笛卡尔积,Java中任意集的笛卡尔积

Do you know some neat Java libaries that allow you to make cartesian product of two (or more) sets?

For example: I have three sets. One with objects of class Person, second with objects of class Gift and third with objects of class GiftExtension.

I want to generate one set containing all possible triples Person-Gift-GiftExtension.

The number of sets might vary so I cannot do this in nested foreach loop.

Under some conditions my application needs to make a product of Person-Gift pair, sometimes it is triple Person-Gift-GiftExtension, sometimes there might even be sets Person-Gift-GiftExtension-GiftSecondExtension-GiftThirdExtension, etc.

解决方案

Edit: Previous solutions for two sets removed. See edit history for details.

Here is a way to do it recursively for an arbitrary number of sets:

public static Set> cartesianProduct(Set>... sets) {

if (sets.length < 2)

throw new IllegalArgumentException(

"Can't have a product of fewer than two sets (got " +

sets.length + ")");

return _cartesianProduct(0, sets);

}

private static Set> _cartesianProduct(int index, Set>... sets) {

Set> ret = new HashSet>();

if (index == sets.length) {

ret.add(new HashSet());

} else {

for (Object obj : sets[index]) {

for (Set set : _cartesianProduct(index+1, sets)) {

set.add(obj);

ret.add(set);

}

}

}

return ret;

}

Note that it is impossible to keep any generic type information with the returned sets. If you knew in advance how many sets you wanted to take the product of, you could define a generic tuple to hold that many elements (for instance Triple), but there is no way to have an arbitrary number of generic parameters in Java.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值