Skip to content

Instantly share code, notes, and snippets.

@nelsonic
Created January 19, 2013 04:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonic/4570709 to your computer and use it in GitHub Desktop.
Save nelsonic/4570709 to your computer and use it in GitHub Desktop.
Coin change problem. Solved in Ruby. using each loop Fewest lines (so far) slightly fancy: times and inject methods used - but no faster than the simple nested until loops Requires RSpec to run.
class Change
def change(amount)
available_coins, coins, remaining_amount = [100,50,25,10,5,1], [], amount
available_coins.each { | coin |
if remaining_amount - coin >= 0
remaining_amount / coin != 0 ? (remaining_amount / coin).to_int.times { coins << coin } : coins << coin
puts "Remaining Amount: #{remaining_amount} | Coin: #{coin}" # console feedback :-)
remaining_amount = amount - coins.inject(:+) # see: http://stackoverflow.com/a/1538801/1148249
end
}
coins
end
end
describe Change do
it "returns [1] for 1" do
expect(subject.change(1)).to eq [1]
end
it "returns [1, 1, 1, 1] for 4" do
expect(subject.change(4)).to eq [1,1,1,1]
end
it "returns [5, 1] for 6" do
expect(subject.change(6)).to eq [5,1]
end
it "returns [25, 10, 10, 1, 1, 1] for 48" do
expect(subject.change(48)).to eq [25,10,10,1,1,1]
end
it "returns [100, 25, 10, 5, 1, 1] for 142" do
expect(subject.change(142)).to eq [100,25,10,5,1,1]
end
it "returns [100,100,50,25,10,1] for 286" do
expect(subject.change(286)).to eq [100,100,50,25,10,1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment