Skip to content

Instantly share code, notes, and snippets.

@AlchemistCamp
Last active September 9, 2022 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save AlchemistCamp/2f82938c25dc9504311a1c1b2a3f00cc to your computer and use it in GitHub Desktop.
Save AlchemistCamp/2f82938c25dc9504311a1c1b2a3f00cc to your computer and use it in GitHub Desktop.
Lesson 1 source
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