【发布时间】:2015-02-17 03:47:45
【问题描述】:
我需要有关我的 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);
}
}
【问题讨论】: