Reputation: 143
The algorithm is suppose to ask the middle letter of the English alphabet, in my program its N
. At this point it asks the user whether:
The guess is correct
The letter is earlier in the alphabet.
The letter is later in the alphabet
When trying to guess Jose
, it will first ask about N
. I choose option 2 which then gives me G
. I then choose option 3 which then gives me Q
. I then choose option 2 which then gives me I
. I then choose option 3 which then gives me R
. If I choose option 2, it gives me R
again, and basically I'm stuck between R
and I
. How can I fix my algorithm to properly provide all letters available?
My code is the following:
int let = 26/2;
if(n != 0) {
//Correct guess
if(n == 3) {
aLetter = alphabet[let];
actualLetter = Character.toString(aLetter);
aName.add(actualLetter);
}
//earlier in alphabetical order
else if(n == 2) {
let /= 2;
}
//later in alphabetical order
else if(n == 1) {
for(int i = let; i < 27; i++){
r += 1;
}
r /= 2;
let += r;
r=0;
}
} //done guessing
else if (n == 0) {
for(String str: aName) {
result3 += str;
}
}
Any help and or advice would be great. Thanks!
Upvotes: 0
Views: 188
Reputation: 11132
Say the letter of the alphabet (represented by --- etc.
) being guessed is "s" (represented by +
). The computer will first guess in the middle (let
= 13, represented by |
).
-------------|---+--------
You tell the computer to guess higher.
With the code
for(int i = let; i < 27; i++) {
r += 1;
}
r /= 2;
let += r;
r=0;
which can be shortened to
let += (26 - let) / 2;
the computer will guess halfway to the end (let
= 19):
-------------|---+-|------
So far so good.
Now, you tell it to guess lower. The computer knows it's higher than 13 and lower than 19, so it should guess halfway in between. However, the code you have does not do that.
let /= 2;
makes let
be (int)(19 / 2)
, i.e., 9.
---------|---|---+-|------
What you want is let
= 16
-------------|--|-+|------
Let's say you successfully got to
-------------|--|-+|------
with the most recent guess being 16. You tell the computer to guess higher. With the code
let += (26 - let) / 2;
let
will become 21.
-------------|--|-+|-|----
What you want is let
= 18 or 19;
In general, a good algorithm should make let
go up or down by "13 / 2n" each iteration, where "n" is the iteration number (starting at 0
).
You should therefore use the code
int let = 0;
int iteration = 0;
//start loop
//take input
int delta = 13 / Math.pow(2, iteration) + 1;
if(n != 0) {
//if n == 3
else if(n == 2)
{
let -= delta;
}
else if(n == 1)
{
let += delta;
}
}
iteration++;
//end loop
and replace the comments with the code you are already using.
Upvotes: 1