Use a tree structure instead of a list

(Fix for issue #369)
This commit is contained in:
Aldrin Misquitta
2022-01-16 14:21:17 +00:00
committed by GitHub
parent a131b1d864
commit f1c35db0f7

View File

@@ -2,11 +2,14 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Scanner; import java.util.Scanner;
import java.util.stream.Collectors;
/** /**
* ANIMAL * ANIMAL
* <p> * <p>
* Converted from BASIC to Java by Aldrin Misquitta (@aldrinm) * Converted from BASIC to Java by Aldrin Misquitta (@aldrinm)
* The original BASIC program uses an array to maintain the questions and answers and to decide which question to
* ask next. Updated this Java implementation to use a tree instead of the earlier faulty one based on a list (thanks @patimen).
*/ */
public class Animal { public class Animal {
@@ -14,15 +17,18 @@ public class Animal {
printIntro(); printIntro();
Scanner scan = new Scanner(System.in); Scanner scan = new Scanner(System.in);
List<Question> questions = new ArrayList<>(); Node root = new QuestionNode("DOES IT SWIM",
questions.add(new Question("DOES IT SWIM", "FISH", "BIRD")); new AnimalNode("FISH"), new AnimalNode("BIRD"));
boolean stopGame = false; boolean stopGame = false;
while (!stopGame) { while (!stopGame) {
String choice = readMainChoice(scan); String choice = readMainChoice(scan);
switch (choice) { switch (choice) {
case "TREE":
printTree(root);
break;
case "LIST": case "LIST":
printKnownAnimals(questions); printKnownAnimals(root);
break; break;
case "Q": case "Q":
case "QUIT": case "QUIT":
@@ -30,74 +36,78 @@ public class Animal {
break; break;
default: default:
if (choice.toUpperCase(Locale.ROOT).startsWith("Y")) { if (choice.toUpperCase(Locale.ROOT).startsWith("Y")) {
int k = 0; Node current = root; //where we are in the question tree
boolean correctGuess = false; Node previous; //keep track of parent of current in order to place new questions later on.
while (questions.size() > k && !correctGuess) {
Question question = questions.get(k); while (current instanceof QuestionNode) {
correctGuess = askQuestion(question, scan); var currentQuestion = (QuestionNode) current;
if (correctGuess) { var reply = askQuestionAndGetReply(currentQuestion, scan);
previous = current;
current = reply ? currentQuestion.getTrueAnswer() : currentQuestion.getFalseAnswer();
if (current instanceof AnimalNode) {
//We have reached a animal node, so offer it as the guess
var currentAnimal = (AnimalNode) current;
System.out.printf("IS IT A %s ? ", currentAnimal.getAnimal());
var animalGuessResponse = readYesOrNo(scan);
if (animalGuessResponse) {
//we guessed right! end this round
System.out.println("WHY NOT TRY ANOTHER ANIMAL?"); System.out.println("WHY NOT TRY ANOTHER ANIMAL?");
} else { } else {
k++; //we guessed wrong :(, ask for feedback
//cast previous to QuestionNode since we know at this point that it is not a leaf node
askForInformationAndSave(scan, currentAnimal, (QuestionNode) previous, reply);
}
} }
} }
if (!correctGuess) {
askForInformationAndSave(scan, questions);
} }
} }
} }
} }
} /**
* Prompt for information about the animal we got wrong
private static void askForInformationAndSave(Scanner scan, List<Question> questions) { * @param current The animal that we guessed wrong
* @param previous The root of current
* @param previousToCurrentDecisionChoice Whether it was a Y or N answer that got us here. true = Y, false = N
*/
private static void askForInformationAndSave(Scanner scan, AnimalNode current, QuestionNode previous, boolean previousToCurrentDecisionChoice) {
//Failed to get it right and ran out of questions //Failed to get it right and ran out of questions
//Let's ask the user for the new information //Let's ask the user for the new information
System.out.print("THE ANIMAL YOU WERE THINKING OF WAS A "); System.out.print("THE ANIMAL YOU WERE THINKING OF WAS A ");
String animal = scan.nextLine(); String animal = scan.nextLine();
System.out.printf("PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A %s FROM A %s ", animal, questions.get( System.out.printf("PLEASE TYPE IN A QUESTION THAT WOULD DISTINGUISH A %s FROM A %s ", animal, current.getAnimal());
questions.size() - 1).falseAnswer);
String newQuestion = scan.nextLine(); String newQuestion = scan.nextLine();
System.out.printf("FOR A %s THE ANSWER WOULD BE ", animal); System.out.printf("FOR A %s THE ANSWER WOULD BE ", animal);
boolean newAnswer = readYesOrNo(scan); boolean newAnswer = readYesOrNo(scan);
//Add it to our list //Add it to our question store
addNewAnimal(questions, animal, newQuestion, newAnswer); addNewAnimal(current, previous, animal, newQuestion, newAnswer, previousToCurrentDecisionChoice);
} }
private static void addNewAnimal(List<Question> questions, String animal, String newQuestion, boolean newAnswer) { private static void addNewAnimal(Node current,
Question lastQuestion = questions.get(questions.size() - 1); QuestionNode previous,
String lastAnimal = lastQuestion.falseAnswer; String animal,
lastQuestion.falseAnswer = null; //remove the false option to indicate that there is a next question String newQuestion,
boolean newAnswer,
boolean previousToCurrentDecisionChoice) {
var animalNode = new AnimalNode(animal);
var questionNode = new QuestionNode(newQuestion,
newAnswer ? animalNode : current,
!newAnswer ? animalNode : current);
Question newOption; if (previous != null) {
if (newAnswer) { if (previousToCurrentDecisionChoice) {
newOption = new Question(newQuestion, animal, lastAnimal); previous.setTrueAnswer(questionNode);
} else { } else {
newOption = new Question(newQuestion, lastAnimal, animal); previous.setFalseAnswer(questionNode);
}
} }
questions.add(newOption);
} }
private static boolean askQuestion(Question question, Scanner scanner) { private static boolean askQuestionAndGetReply(QuestionNode questionNode, Scanner scanner) {
System.out.printf("%s ? ", question.question); System.out.printf("%s ? ", questionNode.question);
boolean chosenAnswer = readYesOrNo(scanner);
if (chosenAnswer) {
if (question.trueAnswer != null) {
System.out.printf("IS IT A %s ? ", question.trueAnswer);
return readYesOrNo(scanner); return readYesOrNo(scanner);
} }
//else go to the next question
} else {
if (question.falseAnswer != null) {
System.out.printf("IS IT A %s ? ", question.falseAnswer);
return readYesOrNo(scanner);
}
//else go to the next question
}
return false;
}
private static boolean readYesOrNo(Scanner scanner) { private static boolean readYesOrNo(Scanner scanner) {
boolean validAnswer = false; boolean validAnswer = false;
@@ -115,18 +125,26 @@ public class Animal {
return choseAnswer; return choseAnswer;
} }
private static void printKnownAnimals(List<Question> questions) { private static void printKnownAnimals(Node root) {
System.out.println("\nANIMALS I ALREADY KNOW ARE:"); System.out.println("\nANIMALS I ALREADY KNOW ARE:");
List<String> animals = new ArrayList<>();
questions.forEach(q -> { List<AnimalNode> leafNodes = collectLeafNodes(root);
if (q.trueAnswer != null) { String allAnimalsString = leafNodes.stream().map(AnimalNode::getAnimal).collect(Collectors.joining("\t\t"));
animals.add(q.trueAnswer);
System.out.println(allAnimalsString);
} }
if (q.falseAnswer != null) {
animals.add(q.falseAnswer); //Traverse the tree and collect all the leaf nodes, which basically have all the animals.
private static List<AnimalNode> collectLeafNodes(Node root) {
List<AnimalNode> collectedNodes = new ArrayList<>();
if (root instanceof AnimalNode) {
collectedNodes.add((AnimalNode) root);
} else {
var q = (QuestionNode) root;
collectedNodes.addAll(collectLeafNodes(q.getTrueAnswer()));
collectedNodes.addAll(collectLeafNodes(q.getFalseAnswer()));
} }
}); return collectedNodes;
System.out.println(String.join("\t\t", animals));
} }
private static String readMainChoice(Scanner scan) { private static String readMainChoice(Scanner scan) {
@@ -143,17 +161,84 @@ public class Animal {
System.out.println("THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT."); System.out.println("THINK OF AN ANIMAL AND THE COMPUTER WILL TRY TO GUESS IT.");
} }
//Based on https://stackoverflow.com/a/8948691/74057
private static void printTree(Node root) {
StringBuilder buffer = new StringBuilder(50);
print(root, buffer, "", "");
System.out.println(buffer);
}
public static class Question { private static void print(Node root, StringBuilder buffer, String prefix, String childrenPrefix) {
String question; buffer.append(prefix);
String trueAnswer; buffer.append(root.toString());
String falseAnswer; buffer.append('\n');
public Question(String question, String trueAnswer, String falseAnswer) { if (root instanceof QuestionNode) {
var questionNode = (QuestionNode) root;
print(questionNode.getTrueAnswer(), buffer, childrenPrefix + "├─Y─ ", childrenPrefix + "");
print(questionNode.getFalseAnswer(), buffer, childrenPrefix + "└─N─ ", childrenPrefix + " ");
}
}
/**
* Base interface for all nodes in our question tree
*/
private interface Node {
}
private static class QuestionNode implements Node {
private final String question;
private Node trueAnswer;
private Node falseAnswer;
public QuestionNode(String question, Node trueAnswer, Node falseAnswer) {
this.question = question; this.question = question;
this.trueAnswer = trueAnswer; this.trueAnswer = trueAnswer;
this.falseAnswer = falseAnswer; this.falseAnswer = falseAnswer;
} }
public String getQuestion() {
return question;
}
public Node getTrueAnswer() {
return trueAnswer;
}
public void setTrueAnswer(Node trueAnswer) {
this.trueAnswer = trueAnswer;
}
public Node getFalseAnswer() {
return falseAnswer;
}
public void setFalseAnswer(Node falseAnswer) {
this.falseAnswer = falseAnswer;
}
@Override
public String toString() {
return "Question{'" + question + "'}";
}
}
private static class AnimalNode implements Node {
private final String animal;
public AnimalNode(String animal) {
this.animal = animal;
}
public String getAnimal() {
return animal;
}
@Override
public String toString() {
return "Animal{'" + animal + "'}";
}
} }
} }