我需要有关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);
}
}
答案 0 :(得分:1)
您可以使用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");
}
答案 1 :(得分:0)
你基本上想知道数组是否是彼此的字谜。该问题的一般解决方案是对它们进行排序(Arrays.sort
),然后检查它们是否相等。
答案 2 :(得分:-1)
对不起。我没有很好地阅读这个问题。要做你想做的事,你可以按最大和最小的顺序排列每个数组中的值,然后检查它们是否相等。
此代码循环遍历数组,并使用其他数组元素检查每个元素。
boolean equal = true;//If true after for then it is equal if false then it is not equal.
for(int i = 0; i < a.length; a++){
if(!a[i].equals(b[i])){
equal = false;
break;
}
}
击> <击> 撞击>