本来以为是一个比较复杂的算法,后来想了想,通过减法和递归就可以轻轻松松解决了。
题目地址:http://hero.pongo.cn/Question/Details?ID=142&ExamID=140
题目详情
废话少说,上代码
class CoverNumber
def initialize(a, b, x, y)
@a, @b, @x, @y = a, b, x, y
@a_b = (@a..@b).to_a
end
def count
(@x..@y).to_a.select{|i| can_plus_by_a_b(i)}.count
end
private
def can_plus_by_a_b(number)
return false if number <= 0
return true if @a_b.include? number
@a_b.each do |i|
return true if can_plus_by_a_b(number - i)
end
false
end
end
describe "test cover number" do
it "should get 8 if a = 8, b = 10, x = 3 , y = 20" do
cn = CoverNumber.new(8, 10, 3, 20)
cn.count.should == 8
end
end