如何在两个数组之间的不同位置打印匹配元素?(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); 

如果这两个数组都很小,即每个数组只包含五个元素,则需要一个嵌套循环。对于随机数数组中的每个元素,遍历猜测数组。

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

当然,您可以像示例中那样增加计数,并显示匹配的元素数量,而不是输出匹配的值。