【发布时间】:2019-03-09 15:55:43
【问题描述】:
定义:
- Bulls:如果数组中匹配的数字在相同的位置
- 奶牛:如果数组中匹配的数字在不同的位置
对于我的任务,我正在尝试编写计算公牛和奶牛数量的函数。
例如:
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};
getNumOfBulls(secret, guessOne) returns 1.
getNumOfBulls(secret, guessTwo) returns 3.
getNumOfBulls(secret, guessThree) raises an exception.
getNumOfBulls(guessThree, guessFour) returns 2.
getNumOfCows(secret, guessOne) returns 2.
getNumOfCows(secret, guessTwo) returns 0.
getNumOfCows(secret, guessThree) raises an exception.
getNumOfCows(guessThree, guessFour) returns 2.
我能够完成第一部分,但我无法计算奶牛的数量。我的代码包括奶牛数量中的公牛数量,因此 getNumOfCows(secret, guessTwo) 返回 3 而不是 0。
这是我的代码:
// A method that gets the number of bulls in a guess
public static int getNumOfBulls(int[] secretNumber, int[] guessedNumber) {
// Initialize and declare a variable that acts as a counter
int numberOfBulls = 0;
if (guessedNumber.length == secretNumber.length) {
// Compare the elements of both arrays at position i
for (int i = 0; i < guessedNumber.length; i++) {
int guessedDigit = guessedNumber[i];
int secretDigit = secretNumber[i];
if (guessedDigit == secretDigit) {
// Update the variable
numberOfBulls++;
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfBulls;
}
// 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;
if (guessedNumber.length == secretNumber.length) {
// Loop through all the elements of both arrays to see if there is any matching digit located at different positions
for (int i = 0; i < guessedNumber.length; i++) {
for (int j = 0; j < secretNumber.length; j++) {
int guessedDigit = guessedNumber[i];
int secretDigit = secretNumber[j];
if (guessedDigit == secretDigit) {
// Update the varaible
numberOfCows++;
}
}
}
}
else {
// Throw an IllegalArgumentException
throw new IllegalArgumentException ("Both array must contain the same number of elements");
}
return numberOfCows;
}
如何调整第二种方法以获得正确的奶牛数量?
【问题讨论】:
-
你可以从你的数组中构造map,这样更容易实现所描述的问题解决方案
-
@Maya 您的问题需要的输出是什么?
-
我认为您没有理解问题 guessTwo 应该返回 1(或 0,取决于规则)而不是 3 头奶牛。
-
@SyedMehtabHassan 输出显示在示例中
-
@JoakimDanielson 我知道guessTwo 应该返回0,但我的代码却返回3。我不知道如何解决这个问题
标签: java