Last active
June 15, 2022 22:44
-
-
Save veelenga/43465e7ea8954b5ca373d8da2e930ee6 to your computer and use it in GitHub Desktop.
My solution for Chop guess exercise (Programming Elixir 1.3)
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
############################## | |
##Exercise: ModulesAndFunctions-6 | |
defmodule Chop do | |
def guess(actual, lo..hi) when (lo <= hi) and (actual in lo..hi) do | |
current = guessing(lo, hi) | |
IO.puts "Is it #{current}" | |
guess(current, actual, lo..hi) | |
end | |
defp guess(value, actual, _) when value == actual, do: IO.puts value | |
defp guess(value, actual, lo.._) when actual < value, do: guess actual, lo..(value - 1) | |
defp guess(value, actual, _..hi) when actual > value, do: guess actual, (value + 1)..hi | |
defp guessing(lo, hi), do: lo + div(hi - lo, 2) | |
end | |
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 | |
# 273 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, @veelenga ! Although your solution works, I would like to make a couple of notes:
which seems unfair to me, since this is the topic of the next section.
Thus, the solution can be rewritten as follows: