gpt4 book ai didi

java - 如何从n组不同大小的数字中选择n个数字?

转载 作者:行者123 更新时间:2023-11-30 21:41:38 24 4
gpt4 key购买 nike

我正在尝试实现一个应用程序。它需要以下逻辑。

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.SetsJava中的集合上使用笛卡尔积 .

例如

  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 ,您只需 Override toString List的方法

关于java - 如何从n组不同大小的数字中选择n个数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24552723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com