Last active
December 21, 2018 19:23
-
-
Save davidkellis/b87695e8cf8cf7b762a67ea7c60a6b39 to your computer and use it in GitHub Desktop.
guessing game (ruby)
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
# solution to https://www.reddit.com/r/dailyprogrammer/comments/pii6j/difficult_challenge_1/ | |
def main | |
lower_bound = 1 | |
upper_bound = 100 | |
puts "Think of a number between 1 and 100, inclusive." | |
puts "At each guess, answer with 'l' to indicate your number is lower than the guess, 'h' to indicate your number is higher than the guess, or 'y' to indicate the guess is correct." | |
while true | |
guess = (lower_bound + upper_bound) / 2 | |
puts "Is #{guess} your number?" | |
input = gets | |
case input.strip | |
when "l" # the number is less than than `guess` | |
upper_bound = guess - 1 | |
when "h" # the number is greater than `guess` | |
lower_bound = guess + 1 | |
when "y" # `guess` is the correct number, so bail out | |
puts "Your number is #{guess}." | |
break | |
end | |
raise "You lied! You didn't pick a number between 1 and 100!" unless lower_bound <= upper_bound | |
end | |
end | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment