Last active
May 4, 2020 10:06
-
-
Save thundergolfer/6679100a4dcc79d6d2ac976eded6fbbf to your computer and use it in GitHub Desktop.
Coin Change
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Run with `ruby coin_change.rb` | |
# Use to optimally make some number N from a set of candidate integer 'parts' | |
class ChangeMaker | |
def initialize(choices) | |
@choices = choices.sort_by { |n| -n } | |
end | |
def change(amount) | |
bag = [] # holds list of items to return | |
remaining_amount = amount | |
@choices.each do |thing| # counts down finds biggest item first | |
if ((remaining_amount/thing).to_int > 0) | |
then (remaining_amount/thing).to_int.times { bag << thing } | |
puts "Remaining Amount: #{remaining_amount} | thing: #{thing}" | |
remaining_amount = amount - bag.inject(:+) | |
end # bag.inject(:+) sums array items | |
end # stackoverflow.com/a/1538801/1148249 | |
puts "Amount #{amount} >> parts: #{bag}\n\n" | |
return bag | |
end | |
end | |
candidates = [10, 20, 5, 1] | |
calculator = ChangeMaker.new(candidates) | |
bag = calculator.change(530) | |
totals = {} | |
bag.each do |x| | |
if totals.key?(x) | |
totals[x] += 1 | |
else | |
totals[x] = 1 | |
end | |
end | |
puts "Showing counts of each. { <part> => <num in bag> }" | |
puts totals |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment