Last active
August 29, 2015 14:06
-
-
Save GeoffPurdy/27aea56768fe0ed15143 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
MIN=1 | |
MAX=100 | |
MAX_ATTEMPTS=5 | |
won = false | |
guesses = [] | |
secret = rand(MIN..MAX) | |
puts "Guess a number between " + MIN.to_s + " and " + MAX.to_s + ":" | |
begin | |
guess = gets.chomp.to_i | |
guesses.push(guess) | |
if guess < secret | |
puts "Higher:" | |
elsif guess > secret | |
puts "Lower:" | |
elsif guess = secret | |
won = true | |
puts "Bingo!" | |
else puts "Your input is not valid." | |
end | |
end until won or guesses.length == MAX_ATTEMPTS | |
puts "You chose " + guesses.to_s + ". The number was " + secret.to_s |
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
MIN=1 | |
MAX=100 | |
MAX_ATTEMPTS=5 | |
PROMPT = "Please reply h, l, or =" | |
def bsearch(min, max, depth) | |
guess = (min+max)/2 | |
depth += 1; | |
puts "Is the number " + guess.to_s + "? " + PROMPT | |
reply = gets.chomp | |
if (reply == '=') # winner winner | |
return "Bazinga! I guessed " + guess.to_s + " which is correct!" | |
elsif (depth >= MAX_ATTEMPTS) # out of tries | |
return "Fail! All " + depth.to_s + " guesses were wrong." | |
elsif (reply == 'h') #guess < secret | |
return bsearch(guess+1, max, depth) | |
elsif (reply == 'l') #guess > secret | |
return bsearch(min, guess-1, depth) | |
else # invalid input => redo w/ same args | |
puts PROMPT | |
return bsearch(min, max, depth) | |
end | |
end | |
puts "Would you like to play a game? Pick a number between " + MIN.to_s + " and " + MAX.to_s + ":" | |
print bsearch(MIN, MAX, 0).to_s + "\n" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment