Skip to content

Instantly share code, notes, and snippets.

@shaynekang
Created November 30, 2012 18:21
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 shaynekang/4177542 to your computer and use it in GitHub Desktop.
Save shaynekang/4177542 to your computer and use it in GitHub Desktop.
Solution of coin combination issue by paranoiase
# Solution of the coin combination issue.
# by paranoiase
#
# http://www.facebook.com/groups/rubykr
# https://github.com/rubykorea/codingdojo
require 'spec_helper'
class Coin
def initialize(amount)
@amount = amount
end
COINS = [50, 100, 500, 1000, 5000, 10000]
def build_combinations(progress, container, cache = [])
COINS.map do |coin|
combination = progress.dup + [coin]
combination.sort!
next if cache.include? combination
sum = combination.inject(&:+)
if sum == @amount
container << combination
elsif sum < @amount
cache << combination
build_combinations(combination, container, cache)
end
end.compact
end
def count_combinations
[].tap do |container|
build_combinations([], container)
end.uniq.count
end
end
describe Coin do
describe "#count_combinations" do
it "should count all cases of coin combination" do
coin = Coin.new(50)
coin.count_combinations.should == 1
coin = Coin.new(100)
coin.count_combinations.should == 2
coin = Coin.new(150)
coin.count_combinations.should == 2
coin = Coin.new(200)
coin.count_combinations.should == 3
coin = Coin.new(500)
coin.count_combinations.should == 7
coin = Coin.new(1700)
coin.count_combinations.should == 53
# coin = Coin.new(100_000)
# coin.count_combinations.should == 49_330_996
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment