Created
January 19, 2013 03:19
-
-
Save nelsonic/4570556 to your computer and use it in GitHub Desktop.
Coin Change Problem Single Method. Solved in Ruby. Nested until loops.
( requires RSpec)
Available coins are USD: http://en.wikipedia.org/wiki/Coins_of_the_United_States_dollar ;-)
This file contains hidden or 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
class Change | |
def change(amount) | |
available_coins = [100,50,25,10,5,1] # http://en.wikipedia.org/wiki/Coins_of_the_United_States_dollar | |
coins = [] | |
index = 0 | |
coin = available_coins[index] | |
remaining_amount = amount | |
until remaining_amount == 0 | |
until remaining_amount >= coin | |
index = index + 1 | |
coin = available_coins[index] | |
end | |
puts "Amount: #{remaining_amount} | Coin: #{coin}" | |
coins << coin | |
remaining_amount = remaining_amount - coin | |
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