031 Coin sums.sf 709 B

12345678910111213141516171819202122232425262728293031323334
  1. #!/usr/bin/ruby
  2. # Author: Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Website: https://github.com/trizen
  5. # It is possible to make £2 in the following way:
  6. # 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
  7. # How many different ways can £2 be made using any number of coins?
  8. # https://projecteuler.net/problem=31
  9. # Runtime: 0.169s
  10. var target = 200;
  11. var coins = [1, 2, 5, 10, 20, 50, 100, 200];
  12. func num_paths(startsum, lastcoin) is cached {
  13. return 1 if (startsum == target);
  14. var paths = 0;
  15. coins.each { |coin|
  16. if ((lastcoin >= coin) && (startsum <= (target - coin))) {
  17. paths += num_paths(startsum + coin, coin);
  18. }
  19. }
  20. paths;
  21. }
  22. say num_paths(0, target);