Simplify discount budget calculation
This commit is contained in:
parent
f152e166f4
commit
1f3e21b711
@ -5,60 +5,16 @@ module PlanetExpressExpress
|
||||
end
|
||||
|
||||
def limit_discounts(shipments)
|
||||
keys = shipments.keys
|
||||
positions = Array.new(keys.length, 0)
|
||||
shipments[:all].each do |month|
|
||||
available_budget = @limit_per_month
|
||||
|
||||
# We expect all keys to have the same length
|
||||
total_length = shipments[keys.first].length
|
||||
|
||||
for month in 0..(total_length - 1) do
|
||||
reset_positions(positions)
|
||||
budget = @limit_per_month
|
||||
|
||||
while true
|
||||
# Find the next shipment
|
||||
min_index = Float::INFINITY
|
||||
next_val = nil # key_index
|
||||
|
||||
for key_index in 0..(keys.length - 1) do
|
||||
current_position = positions[key_index]
|
||||
|
||||
shipment = shipments[keys[key_index]][month][current_position]
|
||||
next if shipment.nil?
|
||||
|
||||
if shipment[:id] < min_index
|
||||
next_val = key_index
|
||||
min_index = shipment[:id]
|
||||
end
|
||||
month.each do |shipment|
|
||||
if shipment[:discount] > available_budget
|
||||
shipment[:discount] = available_budget
|
||||
end
|
||||
|
||||
break if next_val.nil?
|
||||
# End find the next shipment
|
||||
|
||||
shipment = shipments[keys[next_val]][month][positions[next_val]]
|
||||
positions[next_val] = positions[next_val] + 1
|
||||
|
||||
budget = apply_discount(budget, shipment)
|
||||
available_budget = available_budget - shipment[:discount]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
attr_reader :limit_per_month
|
||||
|
||||
def apply_discount(available_budget, shipment)
|
||||
if shipment[:discount] > available_budget
|
||||
shipment[:discount] = available_budget
|
||||
return 0
|
||||
end
|
||||
available_budget - shipment[:discount]
|
||||
end
|
||||
|
||||
def reset_positions(positions)
|
||||
for i in 0..(positions.length - 1) do
|
||||
positions[i] = 0
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user