ProgrammingElixir1.6-MyTurns/ModulesAndFunctions-6.exs

47 lines
No EOL
1.6 KiB
Elixir
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Im thinking of a number between 1 and 1000.…
# The most efficient way to find the number is to guess halfway between the low and high numbers of the range.
# If our guess is too big, then the answer lies between the bottom of the range and one less than our guess.
# If our guess is too small, then the answer lies between one more than our guess and the end of the range.
# Your API will be guess(actual, range), where range is an Elixir range. Your output should look similar to this:
#
#   iex> 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
# Hints:
# - You may need to implement helper functions with an additional parameter (the currently guessed number).
# - The div(a,b) function performs integer division.
# - Guard clauses are your friends.
# - Patterns can match the low and high parts of a range (a..b=4..8).
defmodule Chop do
def guess(actual, range) do
first..last = range
guess = div(last + first, 2)
guess(actual, first, last)
end
defp guess(actual, first, last) when actual < div(last + first, 2) do
IO.puts "Is it #{div(last + first, 2)}"
guess(actual, first, div(last + first, 2))
end
defp guess(actual, first, last) when actual > div(last + first, 2) do
IO.puts "Is it #{div(last + first, 2)}"
guess(actual, div(last + first, 2), last)
end
defp guess(actual, first, last) do
IO.puts actual
end
end
Chop.guess(273, 1..1000)