binary search function does not reach the the end
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = -1;
while (counter < howManyTimesHalvable(upperLimit - lowerLimit)) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (upperLimit == lowerLimit) {
break;
}
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
counter++;
}
System.out.println("your number is " + upperLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int number) {
boolean isGreater = false;
boolean isCorrectAnswerGiven = false;
while (!isCorrectAnswerGiven) {
System.out.println("Is your number greater than " + (number) + "? (y/n)");
String answer = reader.nextLine();
if (answer.equals("yes") || answer.equals("y")) {
isGreater = true;
isCorrectAnswerGiven = true;
} else if (answer.equals("no") || answer.equals("n")) {
isCorrectAnswerGiven = true;
}
}
return isGreater;
}
public int average(int upperLimit, int lowerLimit) {
return (upperLimit + lowerLimit) / 2;
}
public int average2(int firstNumber, int secondNumber) {
double res = (firstNumber + secondNumber) / 2.0;
Math.round(res);
//System.out.println(res);
return (int) res;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
I have problems debugging this code. In this class, i'm supposed to implement a simple AI which guesses a number based on your answer on the question "is your number higher then " + a number. My problems are a. the code does never reach the end of the range given (so, with a range from 1 to 10, it never guesses 1 or 10) and b. is does not stop in time. Java often repeats a question multiple times, but the program should say the answer as soon as it could know it.
My fault obviously lies in the play-method (I included the whole class for completeness), I just don't know where. My program functions, so a typo or programming fault is not likely. I must do something wrong in my logic, but I don't know what. Does anybody know where the error lies?
java search binary
add a comment |
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = -1;
while (counter < howManyTimesHalvable(upperLimit - lowerLimit)) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (upperLimit == lowerLimit) {
break;
}
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
counter++;
}
System.out.println("your number is " + upperLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int number) {
boolean isGreater = false;
boolean isCorrectAnswerGiven = false;
while (!isCorrectAnswerGiven) {
System.out.println("Is your number greater than " + (number) + "? (y/n)");
String answer = reader.nextLine();
if (answer.equals("yes") || answer.equals("y")) {
isGreater = true;
isCorrectAnswerGiven = true;
} else if (answer.equals("no") || answer.equals("n")) {
isCorrectAnswerGiven = true;
}
}
return isGreater;
}
public int average(int upperLimit, int lowerLimit) {
return (upperLimit + lowerLimit) / 2;
}
public int average2(int firstNumber, int secondNumber) {
double res = (firstNumber + secondNumber) / 2.0;
Math.round(res);
//System.out.println(res);
return (int) res;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
I have problems debugging this code. In this class, i'm supposed to implement a simple AI which guesses a number based on your answer on the question "is your number higher then " + a number. My problems are a. the code does never reach the end of the range given (so, with a range from 1 to 10, it never guesses 1 or 10) and b. is does not stop in time. Java often repeats a question multiple times, but the program should say the answer as soon as it could know it.
My fault obviously lies in the play-method (I included the whole class for completeness), I just don't know where. My program functions, so a typo or programming fault is not likely. I must do something wrong in my logic, but I don't know what. Does anybody know where the error lies?
java search binary
add a comment |
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = -1;
while (counter < howManyTimesHalvable(upperLimit - lowerLimit)) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (upperLimit == lowerLimit) {
break;
}
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
counter++;
}
System.out.println("your number is " + upperLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int number) {
boolean isGreater = false;
boolean isCorrectAnswerGiven = false;
while (!isCorrectAnswerGiven) {
System.out.println("Is your number greater than " + (number) + "? (y/n)");
String answer = reader.nextLine();
if (answer.equals("yes") || answer.equals("y")) {
isGreater = true;
isCorrectAnswerGiven = true;
} else if (answer.equals("no") || answer.equals("n")) {
isCorrectAnswerGiven = true;
}
}
return isGreater;
}
public int average(int upperLimit, int lowerLimit) {
return (upperLimit + lowerLimit) / 2;
}
public int average2(int firstNumber, int secondNumber) {
double res = (firstNumber + secondNumber) / 2.0;
Math.round(res);
//System.out.println(res);
return (int) res;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
I have problems debugging this code. In this class, i'm supposed to implement a simple AI which guesses a number based on your answer on the question "is your number higher then " + a number. My problems are a. the code does never reach the end of the range given (so, with a range from 1 to 10, it never guesses 1 or 10) and b. is does not stop in time. Java often repeats a question multiple times, but the program should say the answer as soon as it could know it.
My fault obviously lies in the play-method (I included the whole class for completeness), I just don't know where. My program functions, so a typo or programming fault is not likely. I must do something wrong in my logic, but I don't know what. Does anybody know where the error lies?
java search binary
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = -1;
while (counter < howManyTimesHalvable(upperLimit - lowerLimit)) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (upperLimit == lowerLimit) {
break;
}
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
counter++;
}
System.out.println("your number is " + upperLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int number) {
boolean isGreater = false;
boolean isCorrectAnswerGiven = false;
while (!isCorrectAnswerGiven) {
System.out.println("Is your number greater than " + (number) + "? (y/n)");
String answer = reader.nextLine();
if (answer.equals("yes") || answer.equals("y")) {
isGreater = true;
isCorrectAnswerGiven = true;
} else if (answer.equals("no") || answer.equals("n")) {
isCorrectAnswerGiven = true;
}
}
return isGreater;
}
public int average(int upperLimit, int lowerLimit) {
return (upperLimit + lowerLimit) / 2;
}
public int average2(int firstNumber, int secondNumber) {
double res = (firstNumber + secondNumber) / 2.0;
Math.round(res);
//System.out.println(res);
return (int) res;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
I have problems debugging this code. In this class, i'm supposed to implement a simple AI which guesses a number based on your answer on the question "is your number higher then " + a number. My problems are a. the code does never reach the end of the range given (so, with a range from 1 to 10, it never guesses 1 or 10) and b. is does not stop in time. Java often repeats a question multiple times, but the program should say the answer as soon as it could know it.
My fault obviously lies in the play-method (I included the whole class for completeness), I just don't know where. My program functions, so a typo or programming fault is not likely. I must do something wrong in my logic, but I don't know what. Does anybody know where the error lies?
java search binary
java search binary
edited Nov 16 '18 at 15:00
pushkin
4,726113055
4,726113055
asked Nov 16 '18 at 14:30
Jay AberlourJay Aberlour
36
36
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
There are some problems with your logic:
- You are calculating
howManyTimesHalvable
in every iteration. This doesn't make sense considering the incrementation ofcounter
. The last possible value for it is always 1 which can be far lower than currentcounter
. - You are checking if upper and lower are the same immediately after asking a question without updating those values. Just move it to the end of the loop.
- Last thing is that you need to increment the average by 1 when updating the
lowerLimit
. If the answer to "Is your number greater thanX
" is yes, then the newlowerLimit
can't beX
.
Corrected method:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = howManyTimesHalvable(upperLimit - lowerLimit);
while (counter > 0) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit)+1;
} else {
upperLimit = average(lowerLimit, upperLimit);
}
if (upperLimit == lowerLimit) {
break;
}
counter--;
}
System.out.println("your number is " + upperLimit);
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339816%2fbinary-search-function-does-not-reach-the-the-end%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are some problems with your logic:
- You are calculating
howManyTimesHalvable
in every iteration. This doesn't make sense considering the incrementation ofcounter
. The last possible value for it is always 1 which can be far lower than currentcounter
. - You are checking if upper and lower are the same immediately after asking a question without updating those values. Just move it to the end of the loop.
- Last thing is that you need to increment the average by 1 when updating the
lowerLimit
. If the answer to "Is your number greater thanX
" is yes, then the newlowerLimit
can't beX
.
Corrected method:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = howManyTimesHalvable(upperLimit - lowerLimit);
while (counter > 0) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit)+1;
} else {
upperLimit = average(lowerLimit, upperLimit);
}
if (upperLimit == lowerLimit) {
break;
}
counter--;
}
System.out.println("your number is " + upperLimit);
}
add a comment |
There are some problems with your logic:
- You are calculating
howManyTimesHalvable
in every iteration. This doesn't make sense considering the incrementation ofcounter
. The last possible value for it is always 1 which can be far lower than currentcounter
. - You are checking if upper and lower are the same immediately after asking a question without updating those values. Just move it to the end of the loop.
- Last thing is that you need to increment the average by 1 when updating the
lowerLimit
. If the answer to "Is your number greater thanX
" is yes, then the newlowerLimit
can't beX
.
Corrected method:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = howManyTimesHalvable(upperLimit - lowerLimit);
while (counter > 0) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit)+1;
} else {
upperLimit = average(lowerLimit, upperLimit);
}
if (upperLimit == lowerLimit) {
break;
}
counter--;
}
System.out.println("your number is " + upperLimit);
}
add a comment |
There are some problems with your logic:
- You are calculating
howManyTimesHalvable
in every iteration. This doesn't make sense considering the incrementation ofcounter
. The last possible value for it is always 1 which can be far lower than currentcounter
. - You are checking if upper and lower are the same immediately after asking a question without updating those values. Just move it to the end of the loop.
- Last thing is that you need to increment the average by 1 when updating the
lowerLimit
. If the answer to "Is your number greater thanX
" is yes, then the newlowerLimit
can't beX
.
Corrected method:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = howManyTimesHalvable(upperLimit - lowerLimit);
while (counter > 0) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit)+1;
} else {
upperLimit = average(lowerLimit, upperLimit);
}
if (upperLimit == lowerLimit) {
break;
}
counter--;
}
System.out.println("your number is " + upperLimit);
}
There are some problems with your logic:
- You are calculating
howManyTimesHalvable
in every iteration. This doesn't make sense considering the incrementation ofcounter
. The last possible value for it is always 1 which can be far lower than currentcounter
. - You are checking if upper and lower are the same immediately after asking a question without updating those values. Just move it to the end of the loop.
- Last thing is that you need to increment the average by 1 when updating the
lowerLimit
. If the answer to "Is your number greater thanX
" is yes, then the newlowerLimit
can't beX
.
Corrected method:
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = howManyTimesHalvable(upperLimit - lowerLimit);
while (counter > 0) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit)+1;
} else {
upperLimit = average(lowerLimit, upperLimit);
}
if (upperLimit == lowerLimit) {
break;
}
counter--;
}
System.out.println("your number is " + upperLimit);
}
edited Nov 17 '18 at 13:35
answered Nov 17 '18 at 10:16
TuramarthTuramarth
1,17741820
1,17741820
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53339816%2fbinary-search-function-does-not-reach-the-the-end%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown