Skip to content

Instantly share code, notes, and snippets.

@jdgo-mars
Created November 29, 2019 19:40
Show Gist options
  • Save jdgo-mars/16390dfafc53ebc33633afb6f42304b8 to your computer and use it in GitHub Desktop.
Save jdgo-mars/16390dfafc53ebc33633afb6f42304b8 to your computer and use it in GitHub Desktop.
Alchemist Camp
defmodule GuessingGame do
def guess(a, b) when a > b, do: guess(b, a)
def guess(low, high) do
answer = IO.gets("Maybe you thinking of #{mid(low, high)}? ")
case String.trim(answer) do
"bigger" ->
bigger(low, high)
"smaller" ->
smaller(low, high)
"yes" ->
IO.puts("Horay! 🥳 🎉 🎊")
_ ->
IO.puts(~s(Type "bigger", "smaller" or "yes"))
guess(low, high)
end
end
defp mid(low, high) do
div(low + high, 2)
end
defp bigger(low, high) do
new_low = min(high, mid(low, high) + 1)
guess(new_low, high)
end
defp 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