如何在Java中的任意数字组上创建笛卡尔积? [英] How to create cartesian product over arbitrary groups of numbers in Java?
问题描述
假设我有2组数字:
{1, 2, 3},
{4, 5}
我想创建一种算法(使用Java),该算法可输出以下6种组合:
I'd like to create an algorithm (in Java) that outputs the following 6 combinations:
1,4
1,5
2,4
2,5
3,4
3,5
可以有任意数量的组以及每个组中任意数量的成员。因此,在上述示例中,有2个组,第一个组具有3个成员,第二个组具有2个成员。另一个示例如下(3组,第一组3个成员,第二和第三组2个成员):
There can be an arbitrary number of groups and an arbitrary number of members within each group. So in the above example, there are 2 groups with the first group having 3 members and the second group having 2 members. Another example is the following (3 groups, 3 members in first groups and 2 members in second and third groups):
{1, 2, 3},
{4, 5},
{6, 7}
这将产生以下12个组合:
Which would yield the following 12 combinations:
1,4,6
1,4,7
1,5,6
1,5,7
2,4,6
2,4,7
2,5,6
2,5,7
3,4,6
3,4,7
3,5,6
3,5,7
如何用Java做到这一点?我正在尝试使用递归,并且已经查看了类似的问题,但我仍然即将出现。谢谢您的帮助! (P.S.这不是用于家庭作业)
How can I do this in Java? I'm trying to use recursion and I've looked at a similar question already but I'm still coming up short. Thanks for the help! (P.S. this is not for a homework assignment)
推荐答案
有点无聊,决定试一试。应该正是您所需要的:
Got a bit bored and decided to give it a shot. Should be exactly what you need:
public static void main(String args[]) {
ArrayList<int[]> input = new ArrayList<int[]>();
input.add(new int[] { 1, 2, 3 });
input.add(new int[] { 4, 5 });
input.add(new int[] { 6, 7 });
combine(input, new int[input.size()], 0);
}
private static void combine(ArrayList<int[]> input, int[] current, int k) {
if(k == input.size()) {
for(int i = 0; i < k; i++) {
System.out.print(current[i] + " ");
}
System.out.println();
} else {
for(int j = 0; j < input.get(k).length; j++) {
current[k] = input.get(k)[j];
combine(input, current, k + 1);
}
}
}
这篇关于如何在Java中的任意数字组上创建笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!