Created
April 22, 2019 08:31
-
-
Save sauravtom/fd5d1b5a45ba99f7734c44039b769050 to your computer and use it in GitHub Desktop.
Alchemist Challenge #1
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
defmodule GuessingGame do | |
# guess between a low number and a high number - > guess the middle | |
#tell the user the guess | |
# if user say yes -> game over | |
# if bigger | |
# if smaller | |
# anything else | |
# elixr allows for multiple definitions of the same functions | |
def guess(a, b) when a > b do | |
guess(b, a) | |
end | |
def guess(low, high) do | |
name = IO.gets "Hi there, what's ur name? \n" | |
case String.trim(name) do | |
"saurav" -> IO.puts "WOW, that's the best name in the world" | |
_ -> IO.puts "Welcome to Elixir #{name} :-)" | |
end | |
answer = IO.gets "Hmm... did you guess #{mid(low, high)} #{name} ? \n" | |
case String.trim(answer) do | |
"bigger" -> bigger(low, high) | |
"smaller" -> smaller(low, high) | |
"yes" -> "YESSSSS!" | |
_ -> IO.puts ~s(Type "bigger", "smaller" or "yes") | |
guess(low, high) | |
end | |
end | |
def mid(low, high) do | |
div low + high, 2 | |
end | |
def bigger(low, high) do | |
new_low = min high, mid(low, high)+1 | |
guess(new_low, high) | |
end | |
def smaller(low, high) do | |
new_high = max low, mid(low, high)-1 | |
guess(low, new_high) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment