我必须建立一个程序来计算用于电话提供商的年度分钟成本,这取决于不同的费率。
例如,一个电话接线员可能有以下费率:
"rates": [
{"price": 15.5, "threshold": 150},
{"price": 12.3, "threshold": 100},
{"price": 8}
],运营商可以有多个关税,而最后一个关税总是没有门槛。
因此,在上面的例子中,前150分钟将按每分钟15.5p收费,下一个100分钟将按每分钟12.3p收费,随后的所有分钟将按8p收费。
因此,如果:
AnnualUsage = 1000总费用为95.55英镑。
我很难想象一种能够适应运营商可能拥有的多重关税的方法,并根据门槛将一个值乘以一个不同的价格。
请帮帮忙!
发布于 2020-02-01 18:26:22
只是另一个选择,我认为这是不言自明的:
rates = [
{price: 15.5, threshold: 150},
{price: 12.3, threshold: 100},
{price: 8}
]
annual_usage = 1000
res = rates.each_with_object([]) do |h, ary|
if h.has_key?(:threshold) && annual_usage > h[:threshold]
annual_usage -= h[:threshold]
ary << h[:threshold] * h[:price]/100
else
ary << annual_usage * h[:price]/100
end
end
res #=> [23.25, 12.3, 60]
res.sum #=> 95.55看看对象。
发布于 2020-02-02 01:09:15
def tot_cost(rate_tbl, minutes)
rate_tbl.reduce(0) do |tot,h|
mins = [minutes, h[:threshold] || Float::INFINITY].min
minutes -= mins
tot + h[:price] * mins
end
end
rate_tbl = [
{ price: 15.5, threshold: 150},
{ price: 12.3, threshold: 100 },
{ price: 8 }
]
tot_cost(rate_tbl, 130) #=> 2015.0 (130*15.5)
tot_cost(rate_tbl, 225) #=> 3247.5 (150*15.5 + (225-150)*12.3)
tot_cost(rate_tbl, 300) #=> 3955.0 (150*15.5 + 100*12.3 + (300-250)*8)如果需要,可以将h[:threshold] || Float::INFINITY替换为
h.fetch(:threshold, Float::INFINITY)发布于 2020-02-01 18:12:38
RATES = [
{price: 15.5, threshold: 150},
{price: 12.3, threshold: 100},
{price: 8}
]
def total_cost(annual_usage)
rate_idx = 0
idx_in_threshold = 1
1.upto(annual_usage).reduce(0) do |memo, i|
threshold = RATES[rate_idx][:threshold]
if threshold && (idx_in_threshold > RATES[rate_idx][:threshold])
idx_in_threshold = 1
rate_idx += 1
end
idx_in_threshold += 1
memo + RATES[rate_idx][:price]
end
end
puts total_cost(1000).to_i
# => 9555关键概念:
each,但reduce更惯用。rate_idx和idx_in_threshold变量通过费率列表跟踪进度。这些信息为您提供了确定是否应该升级到下一层所需的所有信息。另外,避免编写像"price": 15.5这样的散列键--只要去掉引号,它就更地道了。
https://stackoverflow.com/questions/60019563
复制相似问题