Skip to content

Instantly share code, notes, and snippets.

@nelsonic
Last active December 11, 2015 08:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonic/4570855 to your computer and use it in GitHub Desktop.
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
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