[英]How to print matching elements in different positions between two arrays? (java)
我有两个数组。 Array1 保存 5 个随机生成的数字,array2 保存用户输入的 5 个猜测。 我正在尝试计算匹配项,但唯一正在读取的匹配项是处于相同位置的匹配项。 即使我的程序处于不同的位置,我怎样才能让我的程序计算相同的数字?
这是我到目前为止所得到的:
int count = 0;
for (i=0;i<array1.length;i++){
if(array1[i] == array2[i]){
count = count +1;
}
}
System.out.println("matching numbers : "+count);
如果两个数组都很小,即每个数组只包含五个元素,那么你需要一个嵌套循环。 对于随机数数组中的每个元素,遍历 guesses 数组。
int count = 0;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
count++;
}
}
}
System.out.println("matching numbers : "+count);
请注意,当两个数组都很小时,上面的方法是合适的。 当两个数组都很大时,上述方法是不合适的。
您只需要两个数组之间的交集,然后计算结果数组的大小。 因此,您可以避免仅使用 List 类上的retainAll方法手动遍历两个数组:
https://docs.oracle.com/javase/7/docs/api/java/util/List.html#retainAll
这是一个junit测试,展示了如何使用这种方法解决:
@Test
public void TestArraysIntersection() {
Integer[] randomlyGenerated = {1,2,3,4,5};
Integer[] userInput = {4,2,5,3,6};
System.out.println("Randomly generated numbers are: " + Arrays.toString(randomlyGenerated));
System.out.println("Number selected by the user are: " + Arrays.toString(userInput));
List<Integer> intersectionList = new ArrayList<>(Arrays.asList(randomlyGenerated));
intersectionList.retainAll(Arrays.asList(userInput));
System.out.println("Matching numbers are " + intersectionList.size() + " and the values are: "+ intersectionList);
}
测试结果如下:
Randomly generated numbers are: [1, 2, 3, 4, 5]
Number selected by the user are: [4, 2, 5, 3, 6]
Matching numbers are 4 and the values are: [2, 3, 4, 5]
您需要遍历两个数组。 在您的代码中,您将一个数组的每个元素与另一个数组相同位置的元素进行比较,但您必须将一个数组的每个元素与另一个数组的每个元素进行比较,如下所示:
public class MyClass {
public static void main(String args[]) {
int[] numbers = {1, 3, 0, 6};
int[] guesses = {3, 8, 5, 1, 2};
for (int i = 0; i < numbers.length; i++) {
for (int j = 0; j < guesses.length; j++) {
if (numbers[i] == guesses[j]) {
System.out.println("A match on positions "+i+" and "+j+". "+numbers[i]+" = "+guesses[j]);
}
}
}
}
}
输出:
位置 0 和 3 的匹配。1 = 1
位置 1 和 0 的匹配。3 = 3
当然,不是输出匹配的值,而是可以像示例中那样增加计数,并显示匹配的元素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.