Skip to content

Instantly share code, notes, and snippets.

@patrobinson
Created December 20, 2015 12:08
Show Gist options
  • Save patrobinson/b515dd238acfe01434ca to your computer and use it in GitHub Desktop.
Save patrobinson/b515dd238acfe01434ca to your computer and use it in GitHub Desktop.
-module(chop).
-export([guess/3]).
-define(equal(Actual, Guess), Guess == Actual).
-define(lower(Actual, Guess), Guess > Actual).
guess(Actual, First, Last) ->
Guess = binary_guess(First, Last),
higher_lower(Actual, First, Last, Guess).
higher_lower(Actual, _, _, Guess) when ?equal(Actual, Guess) ->
io:fwrite(io_lib:format("~p~n", [Guess]));
higher_lower(Actual, First, _, Guess) when ?lower(Actual, Guess) ->
io:fwrite("Is it ~p~n", io_lib:format("~p", [Guess])),
guess(Actual, First, Guess);
higher_lower(Actual, _, Last, Guess) ->
io:fwrite("Is it ~p~n", io_lib:format("~p", [Guess])),
guess(Actual, Guess, Last).
binary_guess(First, Last) -> First + ((Last - First) / 2).
defmodule Chop do
defmacro is_equal(actual, guess) do
quote do
unquote(guess) == unquote(actual)
end
end
defmacro is_lower(actual, guess) do
quote do
unquote(guess) > unquote(actual)
end
end
def guess(actual, first .. last) do
guess = guestimate(first, last)
higherlower(actual, (first..last), guess)
end
def higherlower(actual, _ .. _, guestimate) when is_equal(actual, guestimate) do
IO.puts guestimate
end
def higherlower(actual, first .. last, guestimate) when is_lower(actual, guestimate) do
IO.puts "Is it #{guestimate(first, last)}"
guess(actual, (first..guestimate))
end
def higherlower(actual, first .. last, guestimate) do
IO.puts "Is it #{guestimate(first, last)}"
guess(actual, (guestimate..last))
end
def guestimate(first, last) do
first + div((last - first), 2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment