Last active
January 1, 2016 23:41
-
-
Save taptapdan/ed85c1ea816f30a61547 to your computer and use it in GitHub Desktop.
CodeCombat: Binary Search Solution
This file contains hidden or 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
| // http://codecombat.com/play/level/binary-search | |
| // Guess the number that the paladin is thinking of each round. | |
| // She will indicate whether the answer is a higher or lower number after each guess. | |
| // She moves to x<39.5 if lower and x>40.5 if higher | |
| // and x==40 if correct. | |
| // The paladin's maxNum property is the upper bound of the number. | |
| var paladin = this.findNearest(this.findFriends()); | |
| while(true) { | |
| var minGuess = 0; // minimum possible number | |
| var maxGuess = paladin.maxNum; // maximum possible number | |
| var midGuess; // your guess | |
| minGuess = minGuess - 1; // include 0 in guess range | |
| while(minGuess <= maxGuess) { | |
| midGuess = Math.ceil( minGuess + ((maxGuess - minGuess) / 2) ); | |
| this.say(midGuess); | |
| // If paladin moves left, guess lower | |
| if (paladin.pos.x < 39.5) { | |
| maxGuess = midGuess; | |
| } | |
| // If paladin moves right, guess higher | |
| else if (paladin.pos.x > 40.5) { | |
| minGuess = midGuess; | |
| } | |
| // We guessed correctly | |
| else { | |
| break; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment