Skip to content

Instantly share code, notes, and snippets.

@caioertai
Last active July 13, 2022 15:02
Show Gist options
  • Save caioertai/9f1308a382183a2e05f735ec8a1ac210 to your computer and use it in GitHub Desktop.
Save caioertai/9f1308a382183a2e05f735ec8a1ac210 to your computer and use it in GitHub Desktop.
# Setting min and max was a condition for making the
# game play by itself.
min_guess = 1
max_guess = 1_000
# Getting a random price that the player can try to guess.
price = rand(min_guess..max_guess)
# Starting a guesses counter, which will be incremented after
# each guess
guesses_counter = 0
# Getting time before game plays out
start_time = Time.now
# loop is the simplest looping keyword from Ruby, it creates a virtually
# infinite loop. It only ever stops if it sees the word `break`. We're calling
# break if the player guesses correctly.
loop do
# This is how we find the best guess, it's the average between the min and max guess.
guess = (max_guess + min_guess) / 2
# Incrementing the guesses count
guesses_counter += 1
if guess == price
## RIGHT guess
puts "It was #{guess}!"
break
else
## WRONG guess
if guess > price # if the guess was OVER the price
max_guess = guess # the new MAX guess is what you guessed.
else # if the guess was UNDER the price
min_guess = guess # the new MIN guess is what you guessed.
end
# By updating the min and max guess, we're also updating the next best
# guess on line 30.
end
end
# Get the time when we finished the game
end_time = Time.now
# Display how many guesses it took
puts "It took you #{guesses_counter} guesses!"
# Show how long, in seconds, it took for the program to guess correctly.
puts "It took you #{end_time - start_time} seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment