Reputation: 375
So I made this game where I pick a random number 1-100 and the computer guesses and I tell it too high, too low, or whatever. It works pretty good, except that it gets stuck in cycles when I try binary search and I can't seem to prevent it. I'll demonstrate:
Say the number is 79. Eventually, the program will ask if the number is 42. No, that's too low. Then it asks if it's 71. Guess higher! Then it asks 82. Nope, lower. Then it goes back to 42 and the cycle repeats over and over. Here's my code (note that it's an excerpt from the full code, so excuse the lack of the importation of JOptionPane and whatnot):
int x = 50;
int y = x;
int[] alreadyGuessed = {};
boolean secondGuess = false;
//The user has to select, too high, too low, correct!
while (secondGuess == false) {
Object[] options = {"Too high", "Too Low", "Correct"};
int pick = JOptionPane.showOptionDialog(null, "Is your number " + x
+ "?", "Guess",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[2]);
for (int positionInList = 0; positionInList >= 100; positionInList++) {
arrayDemo(x, positionInList);
}
if (pick == 0) {
int max = x - 1;
int min = 0;
x = ((max + min) / 2);
}
if (pick == 1) {
int max = 100;
int min = x+1;
x = ((max + min) / 2);
}
if (pick == 2) {
System.out.println("Yay! I win!");
secondGuess = true;
}
}
Upvotes: 1
Views: 192
Reputation: 2325
You need to keep track of both min and max. So in your code, when you say max = 100
or min = 0
, the program is forgetting what the max & min are.
Delete those lines & you should be OK. In essence, you need to remember min & max all the way until you find the answer.
e.g. if the number is 42, min and max will be like:
0..100, guess 50 (too high)
0..49, guess 25 (too low)
26..49, guess 38 (too low)
39..49, guess 44 (too high)
39..43, guess 41 (too low)
42..43, guess 42 WIN!
Notice how both min and max zoom in on the answer. Carrying that information forward is what makes the strategy work.
Upvotes: 1