Last active
December 11, 2015 08:08
-
-
Save nelsonic/4570855 to your computer and use it in GitHub Desktop.
Coin Change Problem Solved in 5 Lines of Ruby. ( Method code on SINGLE Line! ;-)
Do NOT do this in RL kids! ( Seriously Unreadable/Unmaintainable! Simply a Thought Exercise in taking compression to its logical conclusions ... )
Surprisingly fast to execute! :-P
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) | |
available_coins, coins, remaining_amount = [100,50,25,10,5,1], [], amount; available_coins.each { |coin| if ((remaining_amount/coin).to_int > 0) then (remaining_amount/coin).to_int.times { coins << coin }; remaining_amount = amount-coins.inject(:+) end }; return 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