所以我需要制作一个程序,作为一个带有一串数字的策划游戏。这种特殊的方法告诉猜测者用户猜测的数字是多少在实际的密码中。我有代码通过测试只涉及5个唯一数字的猜测,但我无法确定如何用一个以上的数字来计算猜测。例如,密码为12345,猜测为11111,方法应该返回1,但是它返回5.任何建议?这就是我到目前为止所做的:
public int uniqueDigitsFound(String secretNumber, String guess) {
int counter = 0;
int i = 0;
while(i<=secretNumber.length()-1){
if(guess.charAt(i)==secretNumber.charAt(0)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(1)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(2)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(3)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(4)){
counter++;
}
i++;
}
return counter;
}
答案 0 :(得分:0)
在游戏MasterMind中,目标是正确猜测一个秘密序列,不仅匹配值,还匹配序列中的位置。 MasterMind的测试用例如下所示:
SECRET GUESS ANSWER
12345 11111 1
12345 12222 2
12345 12223 2
12345 12345 5
12345 123 3
12345 12345123 5
要解决此问题,请验证猜测中的每个字符是否与秘密中相同位置的值字符匹配:
int correctCharacters(String secret, String guess) {
int correct = 0;
// Make sure the size of the guess does not under or overflow the secret.
for(int i = 0; i < guess.length() && i < secret.length(); i++) {
// If guess and secret match in a position, count as correct.
if(guess.charAt(i) == secret.charAt(i)) {
correct++;
}
}
return correct;
}
答案 1 :(得分:0)
public static int uniqueDigitsFound(String secretNumber, String guess)
{
int counter = 0;
for (int i = 0; i < secretNumber.Length; i++)
{
if (guess.charAt(i) == secretNumber.charAt(i))
counter++;
}
return counter;
}
这个如果数字实际上是唯一的并且不允许相同的数字......你只需要检查之前找到的数字是否找到。
public static int uniqueDigitsFound(String secretNumber, String guess)
{
int[] numbersGuessed = new int[5];
int counter = 0;
for (int x = 0; x < secretNumber.Length; x++)
{
for (int i = 0; i < secretNumber.Length; i++)
{
if (secretNumber.charAt(x) == guess.charAt(x)){
bool uniqueFind = true;
for(int y=0; y<numbersGuessed.Length;y++)
if(numbersGuessed.charAt(y)=secretNumber.charAt(x))
uniqueFind = false;
if(unique){
numbersGuessed[counter] == secretNumber.charAt(x)
counter++;
}
}
}
}
return counter;
}
答案 2 :(得分:0)
有很多方法可以解决这个问题。一种简单的方法就是保留一组已经遇到过的数字,例如
public int uniqueDigitsFound(String secretNumber, String guess) {
int counter = 0;
int i = 0;
Set<Character> charactersThatHaveAlreadyBeenProcessed = new HashSet<>();
while(i<=secretNumber.length()-1){
if (!charactersThatHaveAlreadyBeenProcessed.contains(guess.charAt(i)) {
if(guess.charAt(i)==secretNumber.charAt(0)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(1)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(2)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(3)){
counter++;
}
if(guess.charAt(i)==secretNumber.charAt(4)){
counter++;
}
charactersThatHaveAlreadyBeenProcessed.add(guess.charAt(i));
}
i++;
}
return counter;
}
答案 3 :(得分:0)
除了Jan Nielsen之外。您可以使用以下内容定义检查每个猜测数字的唯一性的方法。它会将每个猜测并将其附加到已存在的数组中,对数组进行排序,然后进行比较“或使用Arraylist”。
某种方法:
int[] str={1 , 2 , .......};
Arrays.sort(str);
for (int i = 1; i < str.length; i++) {
if (str[i] == str[i - 1]) {
System.out.println("Dupe: " + str[i];
}
}