gpt4 book ai didi

java - 识别集合中的数字集合

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:02:55 27 4
gpt4 key购买 nike

我有一组包含数字的集合。说

A = {-2, 5, 6, 8}  
B = {-2, 4}
C = {-2, 4, 6, 8}
D = {1, -2, 15}
E = {1, 4, 15}
F = {1, 15}
G = {2, 5, 6, 15}
H = {2, 6, 15}

现在我想找到一组 4 个数字,并找到属于这个集合的集合。例如,我可以在这里定义一个集合 X = {1, -2, 4, 15} 并且可以看到 B、D、E 和 F 属于这个集合。找到这些集合并不难。

但是,我面临的问题是我想识别该集合中所有长度为 m 的集合。所以实际上,当以上面的例子作为输入时,得到m = 4的算法,和{A,B,C,D,E,F,G,H} code> 作为输入并给我 {B,D,E,F}{B, C}(因为它们都包含集合 {-2, - 4, 6, 8}).

我能得出答案的唯一方法是生成所有可能的 length = 4 集合,并确定每个集合是否适合。这似乎有点生硬。

有什么好的建议吗? (Java 还是 PHP)?

最佳答案

在 Java 中你可以使用 retainAll()集合方法或静态方法 Collections.disjoint(a,b)要么找到包含在两者中的元素,要么只检查它们是否具有共同元素。

例子:

Set<Integer> setA = new HashSet<Integer>();
setA.add( -2 );
setA.add( 5 );
setA.add( 6 );
setA.add( 8 );

Set<Integer> setB = new HashSet<Integer>();
setB.add( -2 );
setB.add( -4 );
setB.add( 6 );
setB.add( 8 );

//fill with all values from setA
HashSet<Integer> setAB = new HashSet<Integer>( setA );
//keep only those values that are contained in setB as well
setAB.retainAll( setB );


System.out.println( setAB ); //prints "[-2, 8, 6]"

System.out.println( "A and B overlap: " + !Collections.disjoint( setA, setB ) ); //prints "A and B overlap: true"

如果您有一组集合,例如List<Set<Integer>>遍历它们并将每一个与输入集进行比较。

或者,您可以使用 Apache Commons Collections 类 CollectionUtils它提供了方便的方法,如 CollectionUtils.containsAny( collection1,collection2 )CollectionUtils.union( collection1,collection2 ) .

Google Guava 可能也有类似的类。

关于java - 识别集合中的数字集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7850992/

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