Skip to content

Instantly share code, notes, and snippets.

@pca2
Created April 22, 2016 18:52
Show Gist options
  • Save pca2/e415b2cefa12f0dad7aa17791981061b to your computer and use it in GitHub Desktop.
Save pca2/e415b2cefa12f0dad7aa17791981061b to your computer and use it in GitHub Desktop.
For given dollar amount make change (USA)
#!/usr/bin/env ruby
def make_change(change_amount)
#denominations to use. Could easily be made a parm.
#Note that these are integers, not floats
denominations = {
Penny: 1,
Nickel: 5,
Dime: 10,
Quarter: 25
}
#Sort by value desc
sorted_denominations = denominations.sort_by {|k,v| -v}.to_h
#convert number into integer to avoid rounding errors
temp_amount = change_amount * 100
results_hash = {}
sorted_denominations.each do |coin_label, coin_value|
coin_frequency = (temp_amount / coin_value).round
results_hash[coin_label] = coin_frequency unless coin_frequency.zero?
temp_amount -= (coin_frequency * coin_value)
end
return results_hash
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment