我正在尝试实现一个应用程序。它需要以下逻辑。
Set1 {1,2,3,4}
Set2 {22,44}
Set3 {8,9,11}
我需要从每个集合中选择一个数字。所以总共有3个数字。但是有很多组合。每次运行应用程序都必须选择不同的组合,以提高复杂性。我的意思是
First run : 1 22 8
Second run : 1 44 9
And so on...
所以我需要找出不同大小集合之间的所有组合。我知道在单个集合中求{1,2,3,4}的方法。
我不知道这个的任何数学算法。在Java或C或c++中有什么逻辑吗?有什么想法吗?
编辑
期望输出:
1 22 8
1 22 9
1 22 11
1 44 8
1 44 9
1 44 11
2 22 8
2 22 9
and so on
可以通过com.google.common.collect.Sets
在Java
中的集合上使用笛卡尔积
例如
Set<Integer> s1=new HashSet<Integer>();
s1.add(1);s1.add(4);s1.add(5);
Set<Integer> s2=new HashSet<Integer>();
s2.add(2);s2.add(3);s2.add(6);
Set<Integer> s3=new HashSet<Integer>();
s3.add(7);s3.add(8);s3.add(8);
Set<List<Integer>> set=Sets.cartesianProduct(s1,s2,s3);
//Give type safety warning
for(List<Integer> l:set){
System.out.println(l);
}
输出[1, 2, 7]
[1, 2, 8]
[1, 3, 7]
[1, 3, 8]
....
注意
如果您想要精确输出为1 2 7
,您只需要List
的Override toString
方法
您可以非常简单地使用三个for
循环,假设您只想输出可能的组合。
for(int i = 0; i < set1.size; i++){
for(int j = 0; j < set2.size; j++){
for(int k = 0; k < set3.size; k++){
System.out.println(set1.toArray()[i] + " " + set2.toArray()[j] + " " + set3.toArray()[k]);
// toArray() represents the set as an array, allowing easy access to its indices
}
}
}
这将以一种简单的方式产生您列出的输出,您可能很容易看到它是如何工作的。对于set1
和set2
中的固定值,输出set3
中的所有可能性。然后从set2
更改为另一个未使用的值,依此类推。
假设你不关心顺序,你想要得到所有的组合,你可以做一些简单的事情:
for (auto it1 : set1)
for (auto it2 : set2)
for (auto it3 : set3)
{
//do stuff with *it1, *it2, *it3
//e.g. printing them
std::cout << *it1 << *it2 << *it3 << std::endl;
//gives you exactly the listing you want
}