In_June

Guess Game w/ Binary Search

Oct 21st, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. /**
  2.  * Simple guessing game with upper and lower bounds. Computer uses a binary search algorithm to find
  3.  * the chosen given number.
  4.  *
  5.  * Created by Steven on 21/10/2014.
  6.  */
  7. public class GuessingGame {
  8.     private final int UPPER_BOUNDS = 100000;
  9.     private final int LOWER_BOUNDS = 0;
  10.     private final int INPUT;
  11.  
  12.     public GuessingGame(int INPUT) {
  13.         if(INPUT > UPPER_BOUNDS || INPUT < LOWER_BOUNDS) {
  14.             System.err.println("Input was out of bounds. Set to " + (UPPER_BOUNDS/2));
  15.             INPUT = UPPER_BOUNDS/2;
  16.         }
  17.         this.INPUT = INPUT;
  18.     }
  19.  
  20.     public void doGuesses() {
  21.         int guess = LOWER_BOUNDS-1;
  22.  
  23.         int searchLength = UPPER_BOUNDS;
  24.         int startIndex = LOWER_BOUNDS;
  25.  
  26.         int guesses = 0;
  27.         while(guess != INPUT) {
  28.             guess = startIndex + (searchLength/2);
  29.             System.out.println("Guessing: " + guess);
  30.             if(INPUT < guess) {
  31.                 searchLength = (searchLength/2);
  32.             } else {
  33.                 startIndex += searchLength/2;
  34.                 searchLength -= (searchLength/2);
  35.             }
  36.  
  37.             guesses++;
  38.         }
  39.         System.out.println("Guessed it in " + guesses + " guesses.");
  40.     }
  41. }
Add Comment
Please, Sign In to add comment