Last active
December 12, 2015 02:29
-
-
Save jah2488/4699591 to your computer and use it in GitHub Desktop.
Coin Changer kata in ruby, attempting to remove all assignments
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
| def changer(change) | |
| [25,10,5,1].map do |coin| | |
| rem = change / coin | |
| change -= (rem * coin) | |
| [coin] * rem | |
| end.flatten | |
| end | |
| # Invocations = 5 | |
| # Assignments = 2 (or 3 if you count the Array Literal) | |
| def inline_changer(amt) | |
| [25,10,5,1].map { |coin| [coin] * ( rem = amt / coin; amt -= (amt / coin) * coin; rem ) }.flatten | |
| end | |
| # Invocations = 7 | |
| # Assignments = 2 | |
| def chr(change) | |
| [25,10,5,1].map { |x| change / x }.zip([25,10,5,1]).map{|x| [x[1]] * x.first }.flatten.inject([]) { |acc, n| acc << n | |
| if acc.inject(n,:+) <= change; acc } | |
| end | |
| # Invocations = 12 | |
| # Assignments = 0 ; However, there is a conditional. | |
| def no_shovel_chr(change) | |
| [25,10,5,1].map { |x| change / x }.zip([25,10,5,1]).map{|x| [x[1]] * x.first }.flatten.inject([]) { |acc, n| acc += [n] | |
| if acc.inject(n,:+) <= change; acc } | |
| end | |
| describe "provides correct change" do | |
| [ | |
| [100, [25,25,25,25]], | |
| [75, [25,25,25]], | |
| [50, [25,25]], | |
| [25, [25]], | |
| [65, [25, 25, 10, 5]], | |
| [37, [25,10,1,1]] | |
| ].each do |set| | |
| context "for #{set[0]}" do | |
| it "changer" do | |
| changer(set[0]).should == set[1] | |
| end | |
| it "inline_changer" do | |
| chr(set[0]).should == set[1] | |
| end | |
| it "ch" do | |
| ch(set[0]).should == set[1] | |
| end | |
| end | |
| end | |
| end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment