Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Simple guessing game with upper and lower bounds. Computer uses a binary search algorithm to find
- * the chosen given number.
- *
- * Created by Steven on 21/10/2014.
- */
- public class GuessingGame {
- private final int UPPER_BOUNDS = 100000;
- private final int LOWER_BOUNDS = 0;
- private final int INPUT;
- public GuessingGame(int INPUT) {
- if(INPUT > UPPER_BOUNDS || INPUT < LOWER_BOUNDS) {
- System.err.println("Input was out of bounds. Set to " + (UPPER_BOUNDS/2));
- INPUT = UPPER_BOUNDS/2;
- }
- this.INPUT = INPUT;
- }
- public void doGuesses() {
- int guess = LOWER_BOUNDS-1;
- int searchLength = UPPER_BOUNDS;
- int startIndex = LOWER_BOUNDS;
- int guesses = 0;
- while(guess != INPUT) {
- guess = startIndex + (searchLength/2);
- System.out.println("Guessing: " + guess);
- if(INPUT < guess) {
- searchLength = (searchLength/2);
- } else {
- startIndex += searchLength/2;
- searchLength -= (searchLength/2);
- }
- guesses++;
- }
- System.out.println("Guessed it in " + guesses + " guesses.");
- }
- }
Add Comment
Please, Sign In to add comment