gpt4 book ai didi

java - 查找两个数组中相同的重数

转载 作者:太空宇宙 更新时间:2023-11-04 14:09:05 25 4
gpt4 key购买 nike

我需要有关 SameElements() 方法的帮助。我需要以随机顺序获取两个用户输入的数组,并查看它们是否具有相同的多重性。

我知道如果它们的长度不同,那么它们就不会有相同的元素。但这就是我所得到的。我的 sameSet() 方法中的代码可以为此修改吗?或者我需要做一些完全不同的事情吗?

 ` /**
* checks whether two arrays have the same elements in some order, with
* the same multiplicities. For example, 1 4 9 16 9 7 4 9 11 and 11 1 4 9 16
* 9 7 4 9 would be considered identical
*
*/

public static boolean sameElements(Integer a[], int sizeA, Integer b[], int sizeB) {
if (a.length != b.length) {
return false;
}
// need help on this, length portion is all I have.
}


/**
* check whether two arrays have the same elements in some order, ignoring
* duplicates. For example, the two arrays 1 4 9 16 9 7 4 9 11 and 11 11 7 9
* 16 4 1 would be considered identical.
*/

public static boolean sameSet(Integer[] a, int sizeA, Integer[] b, int sizeB) {

HashSet<Integer> set1 = new HashSet<Integer>(Arrays.asList(a)); // Put arrays a & b into hashset */
HashSet<Integer> set2 = new HashSet<Integer>(Arrays.asList(b));

//Compares the sets to see if they have the same elements

if (set1.equals(set2)) {
System.out.println("The elements of the arrays A and B form the same set.");
} else {
System.out.println("The elements of the arrays A and B do not1 form the same set.");
}
return set1.equals(set2);

}

public static void main() {
final int LENGTH = 30;
int sizeA = 0;
int sizeB = 0;
Integer a[] = new Integer[LENGTH];
Integer b[] = new Integer[LENGTH];
Scanner input = new Scanner(System.in);
Scanner in = new Scanner(System.in);

System.out.println("Please fill up values for array a, Q to quit: "); //Gather user input for array A
while (input.hasNextInt() && sizeA < a.length) {
a[sizeA] = input.nextInt();
sizeA++;
}
System.out.println("# of values in array A:" + sizeA + "\n");

System.out.println("Please fill up values for array b, type in Q to quit: "); //Gather user input for array B
while (in.hasNextInt() && sizeB < b.length) {
b[sizeB] = in.nextInt();
sizeB++;
}
System.out.println("# of values in array B:" + sizeB);
//Take the user input and test it through each method
equals(a, sizeA, b, sizeB);
sameSet(a, sizeA, b, sizeB);
sameElements(a, sizeA, b, sizeB);


}
}

最佳答案

您可以使用 Set 的 containsAll 方法轻松实现它。我写了下面的程序。请检查是否对您有帮助。

    Set a = new HashSet<Integer>();
Set b = new HashSet<Integer>();
a.add(1);
a.add(2);
a.add(3);

b.add(3);
b.add(2);
b.add(1);
if(a.containsAll(b) && b.containsAll(a))
{
System.out.println("Same elements in both");
}
else
{
System.out.println("Not same elements in both");
}

关于java - 查找两个数组中相同的重数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28554308/

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