-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathBinarySearchGuessingGame.java
63 lines (50 loc) · 2.02 KB
/
BinarySearchGuessingGame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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);
int average = 0;
// write the guessing logic here
while(lowerLimit <= upperLimit){
average = this.average(lowerLimit, upperLimit);
if(this.isGreaterThan(average) == true){
lowerLimit = average + 1;
}else{
upperLimit = average - 1;
}
}
System.out.println("The number you're thinking of is " + lowerLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int value){
System.out.println("Is your number greater than " + value + "? (y/n)");
String answer = this.reader.nextLine();
if(answer.equals("y")){
return true;
}else{
return false;
}
}
public int average(int firstNumber, int secondNumber){
int average = (firstNumber + secondNumber)/2;
return average;
}
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;
}
}