Skip to content

Instantly share code, notes, and snippets.

@ughitsaaron
Last active December 22, 2018 23:31
Show Gist options
  • Save ughitsaaron/a4e71d59c77c7fbc5a50bed89c200a79 to your computer and use it in GitHub Desktop.
Save ughitsaaron/a4e71d59c77c7fbc5a50bed89c200a79 to your computer and use it in GitHub Desktop.
Programming Elixir Exercises
defmodule Mod do
def sum(0), do: 0
def sum(n), do: n + sum(n - 1)
def gcd(x, 0), do: x
def gcd(x, y), do: gcd(y, rem(x, y))
end
defmodule Chop do
# base case: if g equals actual then return g
def guess(actual, _, g) when actual == g, do: g
# when guess is too high, slice range in half by lower bounds
def guess(actual, rng, g) when g > actual do
lower.._ = rng
guess actual, lower..midpoint(rng)
end
# when guess is too low, slice range in half by upper bounds
def guess(actual, rng, g) when g < actual do
_..upper = rng
guess actual, midpoint(rng)..upper
end
# make guess
def guess(actual, rng) do
g = midpoint rng
IO.puts "Guessing #{g}"
guess actual, rng, g
end
# find midpoint of a range
def midpoint(first..last), do: div (first + last), 2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment