\$\begingroup\$
\$\endgroup\$
How many different ways can 200 be made using any number of coins? The possible denominations are 1, 2, 5, 10, 20, 50, 100, 200.
-module(coins).
-export([coins/2]).
coins(_, 0) -> 1;
coins([], _) -> 0;
coins(_, Goal) when Goal < 0 -> 0;
coins([H|T], Goal) ->
coins([H|T], Goal-H) + coins(T, Goal).
The call is:
1> c(coins).
2> coins:coins([1, 2, 5, 10, 20, 50, 100, 200], 200).
73682
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Nov 6, 2015 at 10:15
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
You can easily give more structure to your code:
-module(coins).
-export([coins/2]).
-spec coins([CoinValue::integer()], Goal::integer()) -> Combinations::integer().
coins(_, 0) -> 1;
coins([], _) -> 0;
coins(_, Goal) when Goal < 0 -> 0;
coins([CoinValue|Rest], Goal) ->
WithCoinValue = coins([H|T], Goal-H),
WithoutCoinValue = coins(T, Goal),
WithCoinValue + WithoutCoinValue.
answered Nov 6, 2015 at 12:47
-
\$\begingroup\$ Thanks for the
spec
. About new variables(WithCoinValue, WithoutCoinValue) IMHO, they are spare. But this is a question of taste \$\endgroup\$kharandziuk– kharandziuk2015年11月06日 13:32:58 +00:00Commented Nov 6, 2015 at 13:32
default