Created
January 19, 2013 03:00
-
-
Save nelsonic/4570492 to your computer and use it in GitHub Desktop.
Coin Change Problem solved in Ruby using While and Until.
US Coins. Requires RSpec. To run:
$ rspec change_spec.rb
Not the fewest lines possible but definitely easy for others to understand. ;-)
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
class Change | |
def change(amount) | |
coins = [] | |
remaining_amount = amount | |
while remaining_amount != 0 | |
coin = get_highest_coin(remaining_amount) | |
coins << coin | |
remaining_amount = remaining_amount - coin | |
end | |
coins | |
end | |
def get_highest_coin(amount) | |
available_coins = [100,25,10,5,1] | |
index = 0 | |
coin = available_coins[index] | |
until amount >= coin | |
index = index + 1 | |
coin = available_coins[index] | |
end | |
puts "Amount: #{amount} | Coin: #{coin}" | |
coin | |
end | |
end | |
describe Change do | |
it "returns the highest coin given the amount 30 should be 25" do | |
expect(subject.get_highest_coin(30)).to eq 25 | |
end | |
it "returns the highest coin given the amount 11 should be 10" do | |
expect(subject.get_highest_coin(11)).to eq 10 | |
end | |
it "returns the highest coin given the amount 7 should be 5" do | |
expect(subject.get_highest_coin(7)).to eq 5 | |
end | |
it "returns the highest coin given the amount 1 should be 1" do | |
expect(subject.get_highest_coin(1)).to eq 1 | |
end | |
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 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment