【发布时间】:2019-08-02 22:56:02
【问题描述】:
对于我的任务,我需要编写一个方法来返回在 2 个数组之间找到的奶牛数量(见下面的定义)。如果输入数组具有不同数量的元素,则该方法应抛出带有适当消息的 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;
}
【问题讨论】:
-
为什么不应该把secret[0]和guessTwo[3]视为牛?它们不是公牛,因为它们不在同一个位置,它们在不同的位置和相同的编号。这满足您的定义。
-
@Y.Kakdas 可能是因为在两个数组的位置 0 也有一个 2,所以它已经被认为是公牛。
-
这是stackoverflow.com/questions/55079127/… 的副本,我相信即使尚未获得批准,您也可以在那里找到正确答案。
-
您的代码需要一种方法来存储哪些元素被认为是公牛,而不是将它们与任何其他元素进行比较以找到错误的母牛。
-
@Y.Kakdas 因为 secret[0] 已经被 guessTwo[0] 视为公牛
标签: java arrays if-statement continue