Skip to content

Instantly share code, notes, and snippets.

@codeincontext
Last active January 11, 2016 00:22
Show Gist options
  • Select an option

  • Save codeincontext/6665176 to your computer and use it in GitHub Desktop.

Select an option

Save codeincontext/6665176 to your computer and use it in GitHub Desktop.
Programming Elixir binary chop exercise
defmodule Chop do
def guess(actual, a..b) do
mid = midpoint(a, b)
IO.puts "Is it #{mid}?"
compare actual, a..b, mid
end
defp compare(actual, _.._, current) when current == actual do
IO.puts "Got it! It was #{actual}"
end
defp compare(actual, a.._, current) when actual < current do
guess actual, a..current
end
defp compare(actual, _..b, current) when actual >= current do
guess actual, current..b
end
defp midpoint(a, b) do
a + div(b - a, 2)
end
end
#iex(1)> Chop.guess(273, 1..1000)
#Is it 500?
#Is it 250?
#Is it 375?
#Is it 312?
#Is it 281?
#Is it 265?
#Is it 273?
#Got it! It was 273
@AndrewIngram
Copy link

you don't need the guard on your first compare, you can just do compare(actual, _.._, actual)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment