Skip to content

Instantly share code, notes, and snippets.

@indiebrain
Last active November 2, 2015 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indiebrain/f80d77328a96dc7c2564 to your computer and use it in GitHub Desktop.
Save indiebrain/f80d77328a96dc7c2564 to your computer and use it in GitHub Desktop.
# IntegerGuesser.guess(number, range)
# Conducts a binary serach within the range for the integer and
# reports its path along the way.
#
# EX:
# iex(1)> IntegerGuesser.guess(273, 1..1000)
# Is it 500?... Nope
# Is it 249?... Nope
# Is it 375?... Nope
# Is it 311?... Nope
# Is it 279?... Nope
# Is it 263?... Nope
# Is it 271?... Nope
# Is it 275?... Nope
# Is it 272?... Nope
# Is it 274?... Nope
# Is it 272?... Nope
# "It's 273!"
defmodule IntegerGuesser do
def guess(actual, first..last)
when actual in first..last do
next_guess(actual, div(last, 2), first..last)
end
defp next_guess(actual, guess, _)
when guess == actual do
"It's #{guess}!"
end
defp next_guess(actual, guess, first..last)
when guess < actual do
report_guess(guess)
next_guess(actual, div(last+guess, 2)+1, guess+1..last)
end
defp next_guess(actual, guess, first..last)
when guess > actual do
report_guess(guess)
next_guess(actual, div(guess+first, 2)-1, first..guess-1)
end
defp report_guess(guess) do
IO.puts("Is it #{guess}?... Nope")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment