1
\$\begingroup\$

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
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the spec . About new variables(WithCoinValue, WithoutCoinValue) IMHO, they are spare. But this is a question of taste \$\endgroup\$ Commented Nov 6, 2015 at 13:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.