Guest User

Untitled

a guest
Apr 23rd, 2018
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. #!/usr/bin/ruby
  2. # Calculate the number of ways to make change for a given amount. Pass
  3. # the amount as number of cents as the only parameter.
  4.  
  5. AMOUNT = Integer(ARGV[0])
  6.  
  7. COINS = [10000, 5000, 1000, 500, 200, 100, 50, 25, 10, 5, 1]
  8.  
  9. # Count the number of ways to make change, given the amount and types of
  10. # coins. The coins are passed as an array sorted from largest to smallest
  11. def ways(amount, coins)
  12. # When there is only one type of coin, the only way to make change is to
  13. # divide the amount evenly by the value of the coin.
  14. if coins.length == 1
  15. if amount % coins.first == 0
  16. 1
  17. else
  18. 0
  19. end
  20. else
  21. # With each possible number of the largest coin, calculate the number
  22. # of ways to make change with the second largest through smallest coins
  23. # for the remaining amount recursively, and sum them
  24. 0.step(amount, coins.first).inject(0) do |total_ways, used_amount|
  25. total_ways + ways(amount - used_amount, coins[1..-1])
  26. end
  27. end
  28. end
  29.  
  30. puts ways(AMOUNT, COINS)
Add Comment
Please, Sign In to add comment