So I am trying to sum a total from an array, but once that total is above 8000 it should reduce the amount added by 50%. I seem to be getting the sum of the total from before and after the if condition. Can anyone explain why and how to fix it?
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