Skip to content

Instantly share code, notes, and snippets.

@taptapdan
Last active January 1, 2016 23:41
Show Gist options
  • Select an option

  • Save taptapdan/ed85c1ea816f30a61547 to your computer and use it in GitHub Desktop.

Select an option

Save taptapdan/ed85c1ea816f30a61547 to your computer and use it in GitHub Desktop.
CodeCombat: Binary Search Solution
// 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