如何从n个不同大小的集合中选择n个数字
How to select n numbers from n sets of different size?
我正在尝试实现一个应用程序。它需要以下逻辑。
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
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 处理多个异常集合的C++方法
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何将ampl中的集合表示为c++中的向量
- 如何用数字处理log(0)
- 检查值是否在集合p1和p2中,但不在p3中
- 最高有效数字侧的第N位
- 带过滤器的现代迭代c++集合
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 维护多集中数字的排序列表和另一个集合中的累积总和
- 如何使用 stl 找到不在集合中的最小数字?
- C++显示六个数字的随机集合
- 包含在奇数个集合中的数字
- 如何从n个不同大小的集合中选择n个数字
- 从一组集合{{中选择一组数字{1,2,3}.},{.},{.}}使得所有元素都是唯一的
- 根据存储在集合中的数字计算向量中的int