coin_change.sf 725 B

1234567891011121314151617181920212223242526272829303132333435
  1. #!/usr/bin/ruby
  2. #
  3. ## The classic coin-change problem
  4. #
  5. var denominations = [.01, .05, .1, .25, .5, 1, 2, 5, 10, 20, 50, 100];
  6. func change(n, pos=0, solution=[]) {
  7. var sum = solution.sum;
  8. if (solution.sum == n) {
  9. return [solution]; # found a solution
  10. }
  11. elsif ((sum > n) || (pos > denominations.end)) {
  12. return [];
  13. }
  14. change(n, pos + 1, solution)+
  15. change(n, pos, [solution..., denominations[pos]]);
  16. }
  17. var amount = 0.26;
  18. var solutions = change(amount);
  19. say "There are #{solutions.len} solutions for #{amount} dollars.";
  20. # Find the best solution
  21. var best = solutions.min_by{.len};
  22. say "The best solution is: #{best}";
  23. # Test the best solution
  24. assert_eq(best, [0.01, 0.25]);