Skip to content

Instantly share code, notes, and snippets.

@localshred
Created February 28, 2012 07:22
Show Gist options
  • Save localshred/1930379 to your computer and use it in GitHub Desktop.
Save localshred/1930379 to your computer and use it in GitHub Desktop.
Land of Lisp binary search algorithm in ruby. This is in stark contrast to my verbose approach in the summer of 2011: http://rand9.com/blog/picking-the-right-number-as-quickly-as-possible/
# set some vars
@high = 100
@low = 0
# Simply calc the midpoint (no remainder)
# of the high and low value (bit shift right)
def ask
(@high + @low) >> 1
end
# Set the lower bound to the midpoint plus 1
# and ask again
def higher
@low = ask + 1
ask
end
# Set the upper bound to the midpoint minus 1
# and ask again
def lower
@high = ask - 1
ask
end
# Reset the bounds
def reset
@high = 100
@low = 0
ask
end
# Pick your number, then call ask.
# From there simply say wether the number is higher or lower.
# Use reset to... reset the bounds.
ask
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment