Last active
August 29, 2015 13:56
-
-
Save zporter/9091484 to your computer and use it in GitHub Desktop.
Learning Elixir: Guess a number between a given range
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 Chop do | |
def guess(actual, range = low..high) when actual >= low and actual <= high do | |
_guess(actual, ask(div(low + high, 2)), range) | |
end | |
defp _guess(actual, actual, _) do | |
IO.puts "\nYES! It is #{actual}\n" | |
end | |
defp _guess(actual, answer, (_..high)) when answer < actual do | |
guess(actual, (answer + 1..high)) | |
end | |
defp _guess(actual, answer, (low.._)) when answer > actual do | |
guess(actual, (low..answer - 1)) | |
end | |
defp ask(answer) do | |
IO.puts "Is it #{answer}?" | |
answer | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment