红宝石中的尾递归在有条件之前和有条件之后产生总和?

问题描述 投票:0回答:1

因此,我试图对一个数组的总数求和,但是一旦该总数超过8000,它将减少50%的添加量。我似乎是从if条件之前和之后获取总数的总和。谁能解释为什么以及如何解决它?

arr = [{ add_on: "AWD Drivetrain", price: 2500 }, { add_on: "Sport Package", price: 3500 }, { add_on: "Winter Tire Package", price: 2000 }, { add_on: "GPS Navigation", price: 2000 },]

def calculate_price_recursive(arr)
  prices = arr.sort_by { |x| -x[:price] }.map { |x| x[:price] }
  return recur_sum(prices, 0)
end


def recur_sum(prices, total)
  puts "#{prices}"
  return total if prices.count == 0
  if total < 8000
    prices[0] + recur_sum(prices[1..-1], total + prices[0])
  else
    (prices[0] / 2) + recur_sum(prices[1..-1], total + prices[0])
  end
end
ruby recursion tail-recursion
1个回答
0
投票

\\对于Arr中的Element:

\\\\如果ElementSum <8300

\\\\\\ ElementSum = ElementSum + Element

\\\\ else

\\\\\\ ElementSum = ElementSum +(Element / 2)

© www.soinside.com 2019 - 2024. All rights reserved.