Created
October 11, 2024 17:32
-
-
Save gigamonkey/00b416ff6cefe9bce9cb75114d702f4e to your computer and use it in GitHub Desktop.
A version of Twenty Questions (Four Questions, actually)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class TwentyQuestions { | |
public static final String[] GUESSES = { | |
"a hamster", | |
"a ferret", | |
"a dog", | |
"a cat", | |
"an elephant", | |
"a monkey", | |
"a dolphin", | |
"a whale", | |
"an octopus", | |
"a shark", | |
"a crocodile", | |
"a piranha", | |
"a tortise", | |
"a turtle", | |
"a gecko", | |
"a iguana", | |
}; | |
public static final String[] QUESTIONS = { | |
"Is it a mammal?", | |
"Do people keep it as a pet?", | |
"Does it usually live in a cage?", | |
"Does it run in a wheel?", | |
"Does it like to fetch a ball?", | |
"Does it live on land?", | |
"Does it have a trunk?", | |
"Does it get caught in tuna nets?", | |
"Does it live in water?", | |
"Does it live in the sea?", | |
"Does it have eight arms?", | |
"Does it look like a submerged log?", | |
"Does it have a hard shell?", | |
"Are the Galapagos islands famous for these?", | |
"Can it lick it's own eyeballs?", | |
}; | |
private Scanner scanner = new Scanner(System.in); | |
private boolean ask(String question) { | |
System.out.print(question + " "); | |
return scanner.nextLine().startsWith("y"); | |
} | |
private void makeFinalGuess(String guess) { | |
System.out.print("\nOkay, time to guess. "); | |
if (ask("Is it " + guess + "?")) { | |
System.out.println("I win!"); | |
} else { | |
System.out.println("Dang it; I was so sure that was it."); | |
} | |
System.out.println(); | |
} | |
public void play(String topic, String[] questions, String[] guesses) { | |
double levels = Math.log(guesses.length) / Math.log(2); | |
assert levels % 1 == 0; | |
System.out.println("\n\nLet's play " + (int) levels + " questions. Think of " + topic + " and I'll try to guess it.\n"); | |
int questionIndex = 0; | |
int guessIndex = 0; | |
for (int i = 0; i < levels; i++) { | |
guessIndex <<= 1; | |
if (ask(questions[questionIndex])) { | |
questionIndex += 1; | |
} else { | |
questionIndex += (1 << (int)(levels - (i + 1))); | |
guessIndex++; | |
} | |
} | |
makeFinalGuess(guesses[guessIndex]); | |
} | |
public static void main(String[] args) { | |
new TwentyQuestions().play("an animal", QUESTIONS, GUESSES); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment