-
-
Save AlchemistCamp/2f82938c25dc9504311a1c1b2a3f00cc to your computer and use it in GitHub Desktop.
Lesson 1 source
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 | |
def guess(a, b) when a > b, do: guess(b, a) | |
def guess(low, high) do | |
answer = IO.gets("Hmm... maybe you're thinking of #{mid(low, high)}?\n") | |
case String.trim(answer) do | |
"bigger" -> | |
bigger(low, high) | |
"smaller" -> | |
smaller(low, high) | |
"yes" -> | |
"I knew I could guess your number!" | |
_ -> | |
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