Created
February 20, 2015 00:33
-
-
Save ijoshsmith/92aa703689b8f2d2db44 to your computer and use it in GitHub Desktop.
Count ways to break a dollar using Elixir
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
defmodule Money do | |
@silver_dollar 100 | |
@half_dollar 50 | |
@quarter 25 | |
@dime 10 | |
@nickel 5 | |
@penny 1 | |
def all_coins, do: [@silver_dollar, @half_dollar, @quarter, @dime, @nickel, @penny] | |
def break(amount, coins), do: do_break(amount, coins) | |
defp do_break( _, [@penny] ), do: 1 | |
defp do_break(amount, [coin | smaller_coins]) do | |
0..div(amount, coin) | |
|> Enum.reduce(0, fn(coin_count, sum) -> | |
remaining_amount = amount - coin * coin_count | |
sum + do_break(remaining_amount, smaller_coins) | |
end) | |
end | |
end | |
# Determine how many ways there are to break a dollar. | |
IO.inspect Money.break(100, Money.all_coins) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment