2012-05-04 178 views
1

我有一個問題,Ruby代碼:紅寶石範圍部分

def give_me_all_periods(period, paid_periods) 
    # Can you help me? 
end 

period = [1..10] 
paid_periods = [1..2, 5..8] 
give_me_all_periods(period, paid_periods).should == [1...2, 2...5, 5...8, 8...10] 
+0

將paid_periods始終期間內或在這是否需要驗證呢? –

+2

爲什麼它會從'1..2'變爲'1 ... 2'? –

回答

1
def give_me_all_periods(period, paid_periods) 
     p = period | paid_periods 
     union = p.inject([]){|u,x| u = u|range_to_arr(x)}.sort 
     ranges =[] 
     union.each_cons(2){|a| ranges << Range.new(a[0],a[1]) } 
     ranges 

end 

def range_to_arr(r) 
     [r.first,r.last] 
end 
+0

def give_me_all_periods(period,paid_periods) thresholds =(period + paid_periods).map {| p | [p.begin,p.end]} .flatten.uniq.sort thresholds.zip(thresholds [1,thresholds.size])。map {| pair |對[1]? (pair [0] ... pair [1]):nil} .compact end – arion