Last active
August 29, 2015 14:03
-
-
Save mgreenly/5b24f7a43acc45ef0cfd to your computer and use it in GitHub Desktop.
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
# Programlog Elixir - exercise: ModulesAndFunctions-6 | |
# | |
# Example: | |
# iex> GuessingGame.search(279, 1..1000) | |
# is it 500? | |
# is it 250? | |
# is it 375? | |
# is it 312? | |
# is it 281? | |
# is it 265? | |
# is it 273? | |
# is it 277? | |
# is it 279? | |
# Winner, winner chicken dinner! | |
# :ok | |
defmodule GuessingGame do | |
def midpoint(lo..hi) do | |
div(lo + hi, 2) | |
end | |
def search(actual, range) do | |
guess = midpoint(range) | |
IO.puts "is it #{guess}?" | |
search(actual, range, guess) | |
end | |
def search(actual, _lo..hi, guess) | |
when guess < actual do | |
search(actual, guess..hi) | |
end | |
def search(actual, lo.._hi, guess) | |
when guess > actual do | |
search(actual, lo..guess) | |
end | |
def search(actual, _range, guess) | |
when guess == actual do | |
IO.puts "Winner, winner chicken dinner!" | |
end | |
end |
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
; Programming Elixir - exercise: ModuleAndFunctions-6 in Gauche Scheme | |
; | |
; gosh> (use guessing-game) | |
; gosh> (search 279 1 1000) | |
; is it 500? | |
; is it 250? | |
; is it 375? | |
; is it 312? | |
; is it 281? | |
; is it 265? | |
; is it 273? | |
; is it 277? | |
; is it 279? | |
; Winner, winner chicken dinner! | |
(define-module guessing-game | |
(export search) | |
(define (midpoint lo hi) | |
(quotient (+ lo hi) 2)) | |
(define (search actual lo hi) | |
(let ((guess (midpoint lo hi))) | |
(print "is it " guess "?") | |
(cond ((< guess actual) | |
(search actual guess hi)) | |
((> guess actual) | |
(search actual lo guess)) | |
(else | |
(print "Winner, winner chicken dinner!")))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment