Last active
May 22, 2020 15:00
-
-
Save machineloop/6b7e0ae225b0cb79aee4c55e1e6b7a80 to your computer and use it in GitHub Desktop.
Programming Elixir exercise 6 in modules and functions chapter
This file contains 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
# Prompt directly from book: | |
# Exercise: ModulesAndFunctions-6 | |
# I’m 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, a..b = range, guess) when guess > actual do | |
IO.puts("Is it #{guess}") | |
guess(actual, a..guess, midpoint(range)) | |
end | |
def guess(actual, a..b = range, guess) when guess < actual do | |
IO.puts("Is it #{guess}") | |
guess(actual, guess..b, midpoint(range)) | |
end | |
def guess(actual, a..b = range, guess) when guess == actual do | |
IO.puts("#{guess}") | |
end | |
def guess(actual, a..b = range) when is_integer(actual) and is_map(range) do | |
guess(actual, range, midpoint(range)) | |
end | |
def range_midpoint_index(range) do | |
list = Enum.to_list(range) | |
div(length(list) - 1, 2) | |
end | |
def midpoint(range) do | |
Enum.at(range, range_midpoint_index(range)) | |
end | |
end | |
IO.puts Servy.Guess.guess(273, 1..1000) | |
# Output: | |
# Is it 500 | |
# Is it 500 | |
# Is it 250 | |
# Is it 250 | |
# Is it 375 | |
# Is it 375 | |
# Is it 312 | |
# Is it 312 | |
# Is it 281 | |
# Is it 281 | |
# Is it 265 | |
# Is it 265 | |
# 273 | |
# ok | |
# [Chop] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment