首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据阈值对整数应用不同的乘法器

根据阈值对整数应用不同的乘法器
EN

Stack Overflow用户
提问于 2020-02-01 17:49:42
回答 4查看 75关注 0票数 2

我必须建立一个程序来计算用于电话提供商的年度分钟成本,这取决于不同的费率。

例如,一个电话接线员可能有以下费率:

代码语言:javascript
复制
  "rates":           [
      {"price": 15.5, "threshold": 150},
      {"price": 12.3, "threshold": 100},
      {"price": 8}
    ],

运营商可以有多个关税,而最后一个关税总是没有门槛。

因此,在上面的例子中,前150分钟将按每分钟15.5p收费,下一个100分钟将按每分钟12.3p收费,随后的所有分钟将按8p收费。

因此,如果:

代码语言:javascript
复制
AnnualUsage = 1000

总费用为95.55英镑。

我很难想象一种能够适应运营商可能拥有的多重关税的方法,并根据门槛将一个值乘以一个不同的价格。

请帮帮忙!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-02-01 18:26:22

只是另一个选择,我认为这是不言自明的:

代码语言:javascript
复制
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

看看对象

票数 3
EN

Stack Overflow用户

发布于 2020-02-02 01:09:15

代码语言:javascript
复制
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

代码语言:javascript
复制
rate_tbl = [
  { price: 15.5, threshold: 150},
  { price: 12.3, threshold: 100 },
  { price: 8 }
]

代码语言:javascript
复制
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替换为

代码语言:javascript
复制
h.fetch(:threshold, Float::INFINITY)
票数 2
EN

Stack Overflow用户

发布于 2020-02-01 18:12:38

代码语言:javascript
复制
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

关键概念:

  • 使用可枚举方法(如reduce )逐步构建解决方案。您也可以使用each,但reduce更惯用。
  • 通过rate_idxidx_in_threshold变量通过费率列表跟踪进度。这些信息为您提供了确定是否应该升级到下一层所需的所有信息。

另外,避免编写像"price": 15.5这样的散列键--只要去掉引号,它就更地道了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60019563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档