Skip to content

Instantly share code, notes, and snippets.

@vdeemann
Last active December 12, 2024 00:22
Show Gist options
  • Save vdeemann/f910d8741ef011c11c95b961bc858b96 to your computer and use it in GitHub Desktop.
Save vdeemann/f910d8741ef011c11c95b961bc858b96 to your computer and use it in GitHub Desktop.
programming-elixir-1.6-chapter-6
defmodule Chop do
def guess(actual, range), do: guess_conditional(actual, range, div(Range.size(range),2))
def guess_conditional(actual, range, current_guess) do
if actual > 0 and actual <= Range.size(range) do
guess_helper(actual, range, current_guess)
end
end
def guess_helper(actual, _, current_guess) when current_guess == actual do
"#{current_guess}"
end
def guess_helper(actual, range, current_guess) when current_guess > actual do
IO.puts "Is it #{current_guess} >"
low.._//_ = range
range = low..(current_guess)
#IO.puts "#{range.first}..#{range.last}"
guess_helper(actual, range, div(current_guess+low,2))
end
def guess_helper(actual, range, current_guess) when current_guess < actual do
IO.puts "Is it #{current_guess} <"
_..high//_ = range
range = (current_guess)..high
#IO.puts "#{range.first}..#{range.last}"
guess_helper(actual, range, div(current_guess+high+1,2))
end
end
defmodule Chop do
def guess(actual, range = low..high//_) do
guess = div(low+high, 2)
IO.puts "Is it #{guess}?"
_guess(actual, guess, range)
end
defp _guess(actual, actual, _),
do: IO.puts "Yes, it's #{actual}"
defp _guess(actual, guess, _..high//_)
when guess < actual,
do: guess(actual, guess+1..high)
defp _guess(actual, guess, low.._//_)
when guess > actual,
do: guess(actual, low..guess-1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment