Created
October 15, 2016 09:39
-
-
Save NightlyNexus/b3ccb4005bc8aa962e9cc74ed1668511 to your computer and use it in GitHub Desktop.
This file contains 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
final class GuessGame { | |
public static void main(String[] args) { | |
GuessGame game = new GuessGame(new SimpleGame(13, 0, 100)); | |
System.out.println(game.play()); | |
} | |
private static final class SimpleGame implements GameSetup { | |
private final int known; | |
private final int lowerBound; | |
private final int upperBound; | |
SimpleGame(int known, int lowerBound, int upperBound) { | |
this.known = known; | |
this.lowerBound = lowerBound; | |
this.upperBound = upperBound; | |
} | |
@Override public GameSetup.GuessResult validate(int guess) { | |
if (guess == known) { | |
return GameSetup.GuessResult.CORRECT; | |
} | |
if (guess < known) { | |
return GameSetup.GuessResult.TOO_LOW; | |
} | |
return GameSetup.GuessResult.TOO_HIGH; | |
} | |
@Override public int lowerBound() { | |
return lowerBound; | |
} | |
@Override public int upperBound() { | |
return upperBound; | |
} | |
} | |
interface GameSetup { | |
enum GuessResult { | |
CORRECT, TOO_LOW, TOO_HIGH | |
} | |
GuessResult validate(int guess); | |
int lowerBound(); | |
int upperBound(); | |
} | |
private final GameSetup setup; | |
GuessGame(GameSetup setup) { | |
this.setup = setup; | |
} | |
int play() { | |
return guess(0, setup.lowerBound(), setup.upperBound()); | |
} | |
private int guess(int guessCount, int lowerBound, int upperBound) { | |
int guess = lowerBound + (upperBound - lowerBound) / 2; | |
guessCount++; | |
GameSetup.GuessResult result = setup.validate(guess); | |
switch (result) { | |
case CORRECT: | |
return guessCount; | |
case TOO_LOW: | |
if (guess == upperBound) { | |
throw new IllegalStateException("GuessValidator must be wrong. Cannot guess above: " | |
+ upperBound | |
+ ". Exhausted " | |
+ guessCount | |
+ " guesses."); | |
} | |
return guess(guessCount, guess + 1, upperBound); | |
case TOO_HIGH: | |
if (guess == lowerBound) { | |
throw new IllegalStateException("GuessValidator must be wrong. Cannot guess below: " | |
+ lowerBound | |
+ ". Exhausted " | |
+ guessCount | |
+ " guesses."); | |
} | |
return guess(guessCount, lowerBound, guess - 1); | |
default: | |
throw new AssertionError("Unimplemented GuessResult: " + result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment