对于我的任务,我需要编写一个方法来返回在两个数组之间找到的奶牛数量(见下面的定义)。如果输入数组具有不同数量的元素,则该方法应抛出带有适当消息的IllegalArgumentException。
公牛是在相同位置找到的int数组中的公共数字,而母牛是在不同位置发现的int数组中的公共数字。请注意,如果数字已经是公牛,则不能将其视为牛。
例如,考虑以下数组:
int[] secret = {2, 0, 6, 9};
int[] guessOne = {9, 5, 6, 2};
int[] guessTwo = {2, 0, 6, 2};
int[] guessThree = {1, 2, 3, 4, 5, 6};
int[] guessFour = {1, 3, 4, 4, 0, 5};
1) getNumOfCows(secret, guessOne) returns 2
2) getNumOfCows(secret, guessTwo) returns 0
3) getNumOfCows(secret, guessThree) returns an exception
4) getNumOfCows(guessThree, guessFour) returns 2
我在下面看到的方法适用于示例1和3,但是示例2和4存在一个问题,即getNumOfCows(secret,guessTwo)返回1而不是0,因为secret [0]和guessTwo [3]中的元素被认为是一头牛。有人可以帮我修改我的代码吗?
// A method that gets the number of cows in a guess --- TO BE FIXED
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
// Initialize and declare a variable that acts as a counter
int numberOfCows = 0;
// Initialize and declare an array
int[] verified = new int[secretNumber.length];
if (guessedNumber.length == secretNumber.length) {
// Loop through all the elements of both arrays to see if there is any matching digit
for (int i = 0; i < guessedNumber.length; i++) {
// Check if the digits represent a bull
if (guessedNumber[i] == secretNumber[i]) {
verified[i] = 1;
}
}
for (int i = 0; i < guessedNumber.length; i++) {
// Continue to the next iteration if the digits represent a bull
if (verified[i] == 1) {
continue;
}
else {
for (int j = 0; j < secretNumber.length; j++) {
if (guessedNumber[i] == secretNumber[j] && i != j) {
// Update the variable
numberOfCows++;
verified[i] = 1;
}
}
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfCows;
}
首先通过单独的数组来标记所有公牛,以确保公牛的位置也被计为牛
public static int getNumOfCows(int[] secretNumber, int[] guessedNumber) {
int max = secretNumber.length;
int cows = 0;
int[] checked = new int[max];
for (int i = 0; i < max; i++) {
if (secretNumber[i] == guessedNumber[i]) {
checked[i] = 1;
}
}
for (int i = 0; i < max; i++) {
if (checked[i] == 1) {
continue;
}
for (int j = 0; j < max; j++) {
if (secretNumber[i] == guessedNumber[j]) {
cows++;
checked[i] = 1;
}
}
}
return cows;
}
现在这个答案被接受了,original question可以被投票作为副本被关闭
我在这里从一个重复的问题中发布我的答案,如果这得到批准,那么另一个可以作为副本关闭。
问题是至少在一个阵列中多次出现的元素将无法正确处理。
一个可能的解决方案想法可能就是这个:
此解决方案可能比您当前的解决方案慢一点,但我认为它正常工作。