Last active
January 11, 2016 00:22
-
-
Save codeincontext/6665176 to your computer and use it in GitHub Desktop.
Programming Elixir binary chop exercise
This file contains hidden or 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, 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you don't need the guard on your first compare, you can just do
compare(actual, _.._, actual)